0
我有一個彩色圖像。我想要在圖像觸摸時返回像素值。 所以,我想下面的代碼:如何獲得ios中的圖像像素
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
float x, y;
for (UITouch *touch in touches) {
x = [touch locationInView:imageView].x;
y = [touch locationInView:imageView].y;
if ((x >= 0) && (x <= imageView.frame.size.width) && (y >= 0) && (y <= imageView.frame.size.height)) {
[self getRGBAFromImage:imageView.image atX:x andY:y];
}
}
}
- (void)getRGBAFromImage:(UIImage *)image atX:(int)xx andY:(int)yy {
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
CGFloat red = (rawData[byteIndex] * 1.0) ;
CGFloat green = (rawData[byteIndex + 1] * 1.0) ;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) ;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0)/255.0;
self.textView.textColor=[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];
free(rawData);
}
這將返回像素但不正確的!例如:ImageView中的觸摸顏色是紅色的,但我的textView文本不是紅色。
請幫我確認一下我的代碼。
謝謝!
謝謝!我需要添加CGContextSetBlendMode(context,kCGBlendModeCopy); CGContextTranslateCTM(context,-xx,-yy); ] – user3059729