我有一个UIImageView,我使用UIColor orangeColor绘制它。现在,我有一个函数应该检测点击的像素的pixelColor。
R:1.000000 G:0.501961 B:0.000000
这是我在尝试检测UIOrange的pixelColor时收到的RGB值
应该是。
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是黑色画布。这可能是问题吗?
答案 0 :(得分:1)
你的功能没有任何问题。这是浮点数学的结果。整数255的一半(无符号字节的最大值)为127 / 255.0或128 / 255.0,具体取决于您的舍入方式。其中任何一个都不是0.5。它们分别为0.498039215686275和0.501960784313725。
编辑:我想我应该补充一点,CGImage中的颜色存储为字节,而不是浮点数。因此,当您在UIColor中使用浮点创建橙色时,它会被截断为R:255,G:128,B:0 A:255。当你以浮动形式读回来时,得到1.0 0.501961 B:0.0 A:1.0