在touchesMoved委托中获取像素的RGB

时间:2013-05-22 10:21:12

标签: pixel rgb

我创建了一个选择像素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解决这类问题吗?任何图书馆(如果有的话)?

快速帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

malloc用于图形上下文的像素缓冲区(rawData),但你永远不会free它,所以你基本上泄漏了整个图像的副本,每次触摸移动(这可能很快就会占用很多内存)。

在if语句的末尾添加此内容。

free(rawData);

顺便说一句,您可能只想考虑创建一次位图上下文并重复使用它。每次触摸移动时重绘图像是非常浪费的,如果它仍然保持不变。

答案 1 :(得分:0)

@David:RinoTom是对的。将您的询问作为答案发布是没有意义的。

无论如何,回到你的问题,我为这个问题创建了另一种解决方案。我使用平移手势来移动视图并使用以下方法选取其中心点的RGB:

-(UIColor *)colorOfTappedPoint:(CGPoint)point
{
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [self.view.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    red = pixel[0];
    green = pixel[1];
    blue = pixel[2];
    alpha = pixel[3];

    NSLog(@"%d %d %d %d",red,green,blue,alpha);
    return color;
}

希望这有帮助。

相关问题