我创建了一个选择像素 RGB 值的页面。它允许用户移动他的手指并选择所选图像的像素颜色。还将因此获得的 RGB 设置为显示他的选择的小图像视图。
这是一段代码。
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
// Get Touch location
CGPoint touchLocation = [touch locationInView:touch.view];
// Set touch location's center to ImageView
if (CGRectContainsPoint(imageViewColorPicker.frame, touchLocation))
{
imageViewColorPicker.center = touchLocation;
CGImageRef image = [imageViewSelectedImage.image CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
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),image);
CGContextRelease(context);
int byteIndex = (bytesPerRow * (int)touchLocation.y) + (int)touchLocation.x * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];
imgPixelColor.backgroundColor=[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];
}
}
它正在解决我的问题。但问题是它有时会在手指移动期间Received Memory Warning
在日志窗口中显示 3 次消息时崩溃。
难道我做错了什么?有没有其他方法可以让 RGB 解决此类问题?任何图书馆(如果有)?
快速帮助表示赞赏。