需要為圖表配色、為列表項隨機上色,或做設計驗證時,「生成一個隨機顏色」是很實用的小工具。與其隨便取三個 0~255 的亂數,用 HSB(色相、飽和度、亮度)模型生成的顏色視覺上會協調得多。
UIColor+RandomColor.h
#import <UIKit/UIKit.h>
@interface UIColor (RandomColor)
+ (UIColor *)randomColor;
@end
UIColor+RandomColor.m
#import "UIColor+RandomColor.h"
@implementation UIColor (RandomColor)
+ (UIColor *)randomColor
{
// 色相:0.0 ~ 1.0,涵蓋整個色環
CGFloat hue = (arc4random() % 256) / 256.0;
// 飽和度:0.5 ~ 1.0,避免過於灰白
CGFloat saturation = (arc4random() % 128) / 256.0 + 0.5;
// 亮度:0.5 ~ 1.0,避免過於深黑
CGFloat brightness = (arc4random() % 128) / 256.0 + 0.5;
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
@end
關鍵設計在於後兩個參數被限制在 0.5 到 1.0 之間。如果允許飽和度或亮度接近 0,就會生成一片灰白或漆黑,視覺上完全看不出顏色差異。把範圍收斂後,生成的顏色會明亮且清楚可辨。
arc4random() 的取模範圍是 0~255,除以 256 得到 0.0~0.996;後兩項取模 128 得到 0~127,除以 256 再加 0.5,結果落在 0.5~0.996。所有運算都必須用浮點除法,否則整數除法會讓 hue 永遠是 0。
以下範例示範如何批量產生 1000 張帶編號的純色圖片並存到本地。
- (void)createImage
{
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)[0];
NSLog(@"path = %@", path);
NSString *imgName;
NSString *imgURL;
NSString *markNum;
UIImage *img;
NSData *imgData;
NSError *err;
int width = 1000, height = 1000, fontSize;
CGPoint markPoint;
NSFileManager *fm = [NSFileManager defaultManager];
for (int i = 0; i < 1000; i++) {
// 1. 取一個隨機顏色
UIColor *color = [UIColor randomColor];
[_currentColorImageView setBackgroundColor:color];
// 2. 決定檔名與輸出路徑
imgName = [NSString stringWithFormat:@"%i.jpg", i + 1];
_lblCount.text = imgName;
imgURL = [path stringByAppendingPathComponent:imgName];
// 3. 已存在就跳過,避免重複產生
if ([fm fileExistsAtPath:imgURL]) {
continue;
}
// 4. 取出顏色的 RGBA 分量
const CGFloat *colorComps = CGColorGetComponents(color.CGColor);
markNum = [NSString stringWithFormat:@"%i", i + 1];
fontSize = width / 5;
markPoint = CGPointMake(fontSize / 2, fontSize / 2);
// 5. 建立離屏 context 並填入背景色
UIGraphicsBeginImageContext(CGSizeMake(width, height));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(ctx, colorComps[0], colorComps[1], colorComps[2], colorComps[3]);
CGContextFillRect(ctx, CGRectMake(0, 0, width, height));
// 6. 畫上白色編號
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
[markNum drawAtPoint:markPoint withFont:[UIFont systemFontOfSize:fontSize]];
// 7. 取得圖片並結束 context
img = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = img;
UIGraphicsEndImageContext();
// 8. 寫入檔案
imgData = [NSData dataWithData:UIImageJPEGRepresentation(img, 1.0f)];
[imgData writeToFile:imgURL options:NSDataWritingAtomic error:&err];
if (err) {
NSLog(@"error: %@\nimage:%@", err.localizedDescription, imgName);
} else {
NSLog(@"done: %@", imgName);
}
}
}
colorComps 的長度要檢查。CGColorGetComponents 回傳的分量數量依色彩空間而定:RGB 是 4 個(含 alpha),灰階只有 2 個,若使用 colorWithHue: 建立則對應 RGB 色彩空間,通常安全。但混用不同來源時建議先確認 CGColorGetNumberOfComponents。
改用 UIGraphicsImageRenderer。UIGraphicsBeginImageContext 建立的是 1x 比例的 context,在 Retina 螢幕上會失真。iOS 10 之後應改用:
UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
UIGraphicsImageRenderer *renderer =
[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(width, height) format:format];
UIImage *img = [renderer imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
CGContextRef context = ctx.CGContext;
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, CGRectMake(0, 0, width, height));
}];
大量寫檔不要在主執行緒。1000 張 1000×1000 的 JPEG 會佔用可觀的時間與空間,務必放到背景佇列,並在迴圈中回報進度。
為什麼用 JPEG 而不是 PNG。純色塊用 PNG 檔案更小且無失真;JPEG 對純色反而容易產生壓縮 artifacts。範例沿用 JPEG 只是示範,實務上建議依內容選擇。
路徑寫法。範例中原本硬編碼了桌面路徑,那在 iOS 裝置上不存在。已改回 NSSearchPathForDirectoriesInDomains 取得 App 的 Documents 目錄,這才是沙盒內可寫的位置。