要在圖片背景上直接畫文字,最簡單的做法是沿用 NSString 的 UIKit 繪製擴充,把文字畫進目前的繪圖 context 裡。
-(void)drawAtPoint:(CGPoint)point withFont:(UIFont *)font orientation:(WBOrientation)orient; -(CGPoint)drawInRect:(CGRect)rect withFont:(UIFont *)font orientation:(WBOrientation)orient alignment:(UITextAlignment)align;
第一個方法從指定座標開始畫,適合位置固定的單行文字;第二個方法在指定矩形區域內繪製並可指定對齊方式,適合需要靠齊或換行的場合,回傳值則是實際繪製的高度。
UIFont *font = [UIFont fontWithName:@"Arial" size:18]; NSString *str = @"Hello World"; [str drawAtPoint:CGPointMake(0, 70) withFont:font];
實際操作時,順序很關鍵:先取得背景圖片並把它畫成 context 的內容,接著設定字型與文字顏色,最後在同一個 context 上疊上文字,才不會出現文字被背景蓋掉的情況。
UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; [[UIColor whiteColor] set]; [@"Hello World" drawAtPoint:CGPointMake(0, 70) withFont:font]; UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
這樣就能得到一張已經合成好文字的新圖片,可直接設給 UIImageView 或存成檔案。若文字品質要求較高,可改用 UIGraphicsBeginImageContextWithOptions 並把 scale 設為 0,讓系統依裝置螢幕解析度自動決定倍率。