我有一个UIImageView,并使用UIColor orangeColor绘制它。现在,我有一个功能,应该检测点击像素的pixelColor。绘画时颜色不一致
R:1.000000 G:0.501961 B:0.000000
这是RGB值试图检测的pixelColor为UIOrange
它应该是当我收到。
R:1.000000 G:0.5 B:0.000000
这里是我的功能
- (UIColor *)colorAtPixel:(CGPoint)point {
// Cancel if point is outside image coordinates
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, _overlay_imageView.frame.size.width, _overlay_imageView.frame.size.height), point)) {
return nil;
}
// Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
// Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
NSInteger pointX = trunc(point.x);
NSInteger pointY = trunc(point.y);
CGImageRef cgImage = _overlay_imageView.image.CGImage;
NSUInteger width = CGImageGetWidth(cgImage);
NSUInteger height = CGImageGetHeight(cgImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the pixel we are interested in onto the bitmap context
CGContextTranslateCTM(context, -pointX, -pointY);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
CGContextRelease(context);
// Convert color values [0..255] to floats [0.0..1.0]
CGFloat red = (CGFloat)pixelData[0]/255.0f;
CGFloat green = (CGFloat)pixelData[1]/255.0f;
CGFloat blue = (CGFloat)pixelData[2]/255.0f;
CGFloat alpha = (CGFloat)pixelData[3]/255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
任何想法?
我必须提到,我的UIImageView有一个clearBackground,它的ontop是一个黑色的画布。这可能是问题吗?
我不知道你在这里要求什么类型的帮助。你可以更具体地了解这是一个问题吗? –
是的,我需要比较颜色值与UIColor colornameColor来查看我是否匹配正确的像素。 – digit