您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 小知識:使用 PaintCode 時必須留意的幾件事

編輯:iOS 開發綜合

用 PaintCode 把視覺設計轉成程式碼很吸引人,但實戰下來會踩到幾個坑。這裡整理成三個面向。

一、圖片的選擇標準

並不是所有圖片都適合用程式碼繪製,關鍵在於「用程式碼重現的成本」。如果色塊與線條過多,投入的人力與時間太高,就沒有必要硬做。

實務上的做法是請 UI 提供 SVG 格式的圖片,拖進 PaintCode 生成程式碼。若圖片過於複雜——人像、頭髮、皮膚漸層那種——直接放一張點陣圖反而更合適。

最後一個判斷依據:PaintCode 生成的程式碼高度依賴貝茲曲線。用這個標準去衡量,很容易判斷一張圖適不適合改用程式碼繪製。

二、自動生成程式碼的使用要點

繪製上下文。 UIGraphicsGetCurrentContext() 在 drawRect: 這類方法裡直接使用沒有問題;但若要在任意時機自行建立圖片,就會取不到有效上下文。解法是自己先開一個:

UIGraphicsBeginImageContextWithOptions(
    CGSizeMake(bounds.size.width, bounds.size.height),
    false,
    [UIScreen mainScreen].scale);

繪製速度。 在 4s 這類低端機型上,部分圖片的繪製速度明顯偏慢,會影響使用者體驗。可以考慮放到背景或子執行緒以非同步方式繪製。

圖片緩存。 繪製本身耗時,因此完成後應把結果存到本機;下次使用前先判斷檔案是否存在,有的話直接讀取,沒有才重新繪製。

三、示例程式碼

// 先嘗試從檔案讀取圖片
CGRect bounds = CGRectMake(0, 0, 640, 720);
NSString *path = [self imagePathWithImageName:@"圖片名稱"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

if (image) {
    return image;
}

// 檔案不存在,開始繪製:先建立 context
UIGraphicsBeginImageContextWithOptions(
    CGSizeMake(bounds.size.width, bounds.size.height),
    false,
    [UIScreen mainScreen].scale);

// 取得 PaintCode 自動生成的程式碼所需的 context
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat scale = [self scale];
CGContextScaleCTM(context, scale, scale);
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);

UIColor *color3 = [UIColor colorWithRed:0.936 green:0.936 blue:0.936 alpha:0.5];

CGContextSaveGState(context);
CGContextBeginTransparencyLayer(context, NULL);

// ===== 以下為 PaintCode 自動生成的部分 =====
UIBezierPath *bezierPath = UIBezierPath.bezierPath;
[bezierPath moveToPoint:CGPointMake(0.07, 0)];
// ... 其餘路徑描述省略
bezierPath.usesEvenOddFillRule = YES;
[color3 setFill];
[bezierPath fill];
// ===== 自動生成部分結束 =====

CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);
CGContextAddPath(context, bezierPath.CGPath);

// 最後把圖片存回本機
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
return image;

整體流程就是「快取優先、未命中才繪製」,再搭配非同步與陰影/透明層的細節處理,就能在保留程式碼繪製優勢的同時,把效能成本控制住。

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