我有一個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