您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

在背景為圖片的 view 上直接繪製文字

編輯:iOS 相關資訊

要在圖片背景上直接畫文字,最簡單的做法是沿用 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,讓系統依裝置螢幕解析度自動決定倍率。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved