如何检查UIView或UIImage的像素颜色?

时间:2013-02-06 18:34:53

标签: objective-c uiview bitmap uiimage pixel

我正在尝试检查整个UIView是否填充了一种颜色。我设法使用以下代码块获取UIView的屏幕截图:

UIImage *image = [self imageFromView];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *myImageData = UIImagePNGRepresentation(image);
[fileManager createFileAtPath:@"/Users/{username}/Desktop/myimage.png" contents:myImageData attributes:nil];
[imageData writeToFile:@"/testImage.jpg" atomically:YES];

imageFromView的方法实现如下:

- (UIImage*)imageFromView{  
UIImage *bitmapImage;
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
bitmapImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return bitmapImage; 
}

所以从我的理解,我现在有一个UIView的位图图像。如何访问UIImage的每个像素并检查以确认它实际上是一种颜色(即UIColor blackColor)?

1 个答案:

答案 0 :(得分:1)

如果您返回that answer,以下(未经测试的)代码段应该可以帮助您入门:

- (BOOL) checkForUniqueColor: (UIImage *) image {
    CGImageInspection * inspector = 
        [CGImageInspection imageInspectionWithCGImage: [image CGImage]] ;

    for (CGFloat x = 0 ; x < image.size.width ; x += 1.0f) {
        for (CGFloat y = 0 ; y < image.size.height ; y += 1.0f) {
            CGFloat red ;
            CGFloat green ;
            CGFloat blue ;
            CGFloat alpha ;

            [inspector colorAt: (CGPoint) {x, y}
                           red: &red
                         green: &green
                          blue: &blue
                         alpha: &alpha
            ] ;

            if (red == ... && green == ... && blue == ... && alpha == ...) {

            }
        }
    }
}