How to check pixel color of a UIView or a UIImage?

蹲街弑〆低调 提交于 2019-12-06 13:27:09

问题


I am trying to check if an entire UIView is filled with one color. I managed to get a screenshot of the UIView using the following block of code:

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];

The method implementation for imageFromView is the following:

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

So from what I understand, I now have a bitmap image of the UIView. How do I access each pixel of the UIImage and check to verify it is in fact one color (i.e. UIColor blackColor)?


回答1:


If you go back to that answer, the following (untested) snippet should get you started:

- (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 == ...) {

            }
        }
    }
}


来源:https://stackoverflow.com/questions/14736285/how-to-check-pixel-color-of-a-uiview-or-a-uiimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!