2017-11-17 47 views
0

我有一个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是一个黑色的画布。这可能是问题吗?

+0

我不知道你在这里要求什么类型的帮助。你可以更具体地了解这是一个问题吗? –

+0

是的,我需要比较颜色值与UIColor colornameColor来查看我是否匹配正确的像素。 – digit

回答

1

你的功能没有问题。这是浮点数学的结果。整数255(无符号字节的最大值)中的一半是127/255.0或128/255.0,具体取决于您如何舍入。这两者都不是0.5。他们分别是0.498039215686275和0.501960784313725。

编辑:我想我应该补充一点,在CGImage中的颜色存储为字节,而不是浮动。所以当你用UIColor中的float创建橙色时,它会被截断为R:255,G:128,B:0 A:255。当你读回来作为浮点数得到1.0 0.501961乙:0.0答:1.0

+0

因为很多主要和次要的颜色是由两个因子构建的,所以使用256.0作为常量分母会更好吗? –

+0

否; 255是UInt8的正确最大值。如果你真的关心四舍五入,那么只需以字节为单位指定所有颜色,并且不会有任何转换或精度损失。如果您在显示屏P3上使用宽色,则只需要浮点数。 –

+0

Josh Homann:你能否更新我的函数来处理字节,这样我就可以看到了? – digit