有些互動效果需要「讓文字或按鈕的顏色自動貼合背景」,例如點選一張照片後,讓下方的標籤染上該處的顏色。要做到這件事,得先把圖片還原成一塊可隨意讀取的像素記憶體。以下分享完整做法。
UIImage 是已經繪製好的物件,無法直接查詢某個座標的顏色。我們要做的是建立一個 Bitmap 圖形上下文,把圖片畫進去,然後直接讀取底層的位元組。以 RGBA 格式來說,每個像素佔 4 個位元組,順序固定為紅、綠、藍、透明度,數值範圍 0–255。
void *bitmapData; // 指向像素記憶體的指標
static CGContextRef CreateRGBABitmapContext(CGImageRef inImage) {
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
int bitmapByteCount;
int bitmapBytesPerRow;
size_t pixelsWide = CGImageGetWidth(inImage); // 橫向像素數
size_t pixelsHigh = CGImageGetHeight(inImage); // 縱向像素數
bitmapBytesPerRow = pixelsWide * 4; // 每行位元組數:每個像素 4 個通道各 1 位元組
bitmapByteCount = bitmapBytesPerRow * pixelsHigh;// 整張圖的位元組數
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc(bitmapByteCount); // 配置足夠的記憶體
context = CGBitmapContextCreate(bitmapData,
pixelsWide,
pixelsHigh,
8, // 每個通道 8 bit
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
// Core Foundation 中以 Create 建立的物件需手動釋放
CGColorSpaceRelease(colorSpace);
return context;
}
// 回傳的指標指向一個位元組陣列,每四個元素就是一個像素的 RGBA 值
static unsigned char *RequestImagePixelData(UIImage *inImage) {
CGImageRef img = [inImage CGImage];
CGSize size = [inImage size];
CGContextRef cgctx = CreateRGBABitmapContext(img);
CGRect rect = {{0, 0}, {size.width, size.height}};
// 把圖片繪製到上下文,實際寫入的就是 bitmapData
CGContextDrawImage(cgctx, rect, img);
unsigned char *data = CGBitmapContextGetData(cgctx);
CGContextRelease(cgctx);
return data;
}
// 把原圖縮放成指定尺寸,並解析為像素資料
- (void)setSourceImage:(NSString *)sourceImage ImageWidth:(int)_width ImageHeight:(int)_height {
UIImage *im = [UIImage imageNamed:sourceImage];
UIGraphicsBeginImageContext(CGSizeMake(_width, _height));
[im drawInRect:CGRectMake(0, 0, _width, _height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
width = newImage.size.width;
height = newImage.size.height;
imgPixel = RequestImagePixelData(newImage);
}
這一步為什麼要重新繪製一次?因為取色的成本與像素總量成正比。先把大圖縮到實際顯示尺寸,後續每次查詢的運算量就大幅下降。
- (UIColor *)calColor:(CGPoint)aPoint {
// 索引算法:行號 × 每行位元組數 + 列號 × 4
// 這裡加上 imageView 的偏移,是因為傳入的座標相對於 imageView
int i = 4 * width * round(aPoint.y + imageView.frame.size.height / 2)
+ 4 * round(aPoint.x + imageView.frame.size.width / 2);
int _r = (unsigned char)imgPixel[i];
int _g = (unsigned char)imgPixel[i + 1];
int _b = (unsigned char)imgPixel[i + 2];
NSLog(@"(%f,%f)", aPoint.x, aPoint.y);
NSLog(@"Red : %f Green: %f Blue: %f", _r / 255.0, _g / 255.0, _b / 255.0);
return [UIColor colorWithRed:_r / 255.0f green:_g / 255.0f blue:_b / 255.0f alpha:1.0];
}
關鍵就是那個索引公式:y × 每行位元組數 + x × 4。理解它之後,任何「讀取圖片某點顏色」的需求都能自己寫出來。
- (void)changColor:(UIColor *)color {
int width_;
if (![Util isIpad]) {
width_ = 30;
} else {
width_ = 70;
}
UIGraphicsBeginImageContext(CGSizeMake(width_, width_));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 20, 20);
CGContextSetFillColorWithColor(ctx, color.CGColor);
if (![Util isIpad]) {
CGContextAddArc(ctx, width_ / 2, width_ / 2, 14.5, 0, 6.3, 0);
} else {
CGContextAddArc(ctx, width_ / 2 + 0.5, width_ / 2, 31.3, 0, 6.3, 0);
}
CGContextFillPath(ctx);
self->pickedColorImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
free(bitmapData),否則每次呼叫都會漏一塊記憶體。0 ≤ x < width 且 0 ≤ y < height。