有時需要取得畫面中某個座標的像素顏色,例如做取色器或影像分析。可透過 UIView 的 category 建立 colorOfPoint: 方法。
建立一個 1x1 的 bitmap context,將座標平移到目標點,再以 renderInContext 把 view 的 layer 繪製進去,最後讀取像素的 RGBA 值並轉成 UIColor。
此方法會把 view 渲染到 bitmap,因此結果取決於該 view 的 layer 內容與目前的繪製狀態。若 view 尚未繪製或為透明背景,取到的顏色可能包含 alpha 資訊。
- (UIColor *)colorOfPoint:(CGPoint)point {
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);
[self.layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
}