這幾天在做iPhone App需要用到這個功能,之前買的那本書上沒有特別寫到。在網路上查到了寫法,在這裡記起來以免忘記。
方法一,利用Quartz本身的繪圖函式
- (void) drawText:(NSString *)text x:(float)x y:(float)y { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont(context, "Arial", 20, kCGEncodingMacRoman); CGContextSetTextDrawingMode(context, kCGTextFill); CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0); CGContextSetTextMatrix(context, xform); CGContextSetTextPosition(context, x, y+20); // 20 is y-axis offset pixels CGContextShowText(context, [text UTF8String], strlen([text UTF8String])); }
方法二,利用NSString本身的drawAtPoint函式
- (void) drawText2:(NSString *)text x:(float)x y:(float)y { UIFont *font = [UIFont fontWithName:@"Arial" size:20]; [text drawAtPoint:CGPointMake(x, y) withFont:font]; }
在UIView class裡的darw code
- (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor); NSString *text = @"Hello World!"; [self drawText:text x:50 y:0]; [self drawText2:text x:50 y:30]; }
執行結果:
兩種方法都可以,不過人家說好像第二種方法會比第一種方法多耗一點運算資源。
Tags: iPhone, Mac, Objective-C, Quartz, 程式技術