延續 Quartz2D 的學習,本文示範如何在 iOS 上繪製文字與圖片。透過 drawRect: 方法搭配 UIKit 提供的便利 API,能輕鬆完成各類繪圖任務。
雖然 Quartz2D 提供了 C 語言的文字繪製方法,但由於其座標系與 UIKit 不一致,繪製出來的文字會顛倒,且操作繁瑣,因此不建議直接使用。取而代之,推薦使用 NSString 的 drawInRect:withAttributes: 等便利方法:
- (void)drawRect:(CGRect)rect {
NSString *str = @"這是一段用於示範繪製的測試文字內容";
// 1. 取得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 繪製矩形
CGContextAddRect(ctx, CGRectMake(50, 50, 100, 100));
// 3. 渲染
CGContextStrokePath(ctx);
// 將文字繪製到指定範圍內,一行裝不下會自動換行,超出範圍則不顯示
[str drawInRect:CGRectMake(50, 50, 100, 100) withAttributes:nil];
}
若要自訂文字樣式,可透過屬性字典設定顏色、背景色與字型大小:
NSMutableDictionary *md = [NSMutableDictionary dictionary];
md[NSForegroundColorAttributeName] = [UIColor redColor]; // 文字顏色
md[NSBackgroundColorAttributeName] = [UIColor greenColor]; // 背景顏色
md[NSFontAttributeName] = [UIFont systemFontOfSize:20]; // 字型大小
[str drawAtPoint:CGPointMake(10, 10) withAttributes:md]; // 繪製到指定位置
圖片繪製主要有三種方式,分別對應不同的視覺效果:
以原本的圖片反覆平鋪填滿指定區域:
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"me"];
// 以平鋪方式填滿整個區域
[image drawAsPatternInRect:CGRectMake(0, 0, 320, 480)];
}
將原圖拉伸以填滿指定區域:
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"me"];
[image drawInRect:CGRectMake(0, 0, 200, 200)];
}
將圖片以原始尺寸繪製於指定座標:
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"me"];
[image drawAtPoint:CGPointMake(100, 100)];
}
以上就是 Quartz2D 在文字與圖片繪製上的基礎用法。掌握這些方法後,就能進一步組合出更豐富的自訂介面效果。