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

UIView 取色:如何取得畫面中某一點的顏色

編輯:iOS 開發綜合

取得 UIView 指定點的顏色

有時需要取得畫面中某個座標的像素顏色,例如做取色器或影像分析。可透過 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];
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved