带点击识别器的彩色像素

时间:2015-07-29 13:09:09

标签: ios objective-c

大家好,我的iOS应用程序需要帮助。如何在我点击的位置获取图像的背景颜色(我在UIImageView中插入)。 我创建了一个Tap Gesture Recognizer,但我不知道如何阅读我点击的背景颜色。

1 个答案:

答案 0 :(得分:4)

在控件中添加手势

UITapGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
        [lblSlider addGestureRecognizer:tapRecognizer];
        lblSlider.userInteractionEnabled = YES;

添加此方法后

 - (void)tapGesture:(UITapGestureRecognizer *)recognizer
    {
        CGPoint point1 = [recognizer locationInView:recognizer.view];

        UIGraphicsBeginImageContext(recognizer.view.bounds.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [recognizer.view.layer renderInContext:context];

        int bpr = (int)CGBitmapContextGetBytesPerRow(context);
        unsigned char * data = CGBitmapContextGetData(context);
        if (data != NULL)
        {
            int offset = bpr*round(point1.y) + 4*round(point1.x);
            int blue = data[offset+0];
            int green = data[offset+1];
            int red = data[offset+2];
            int alpha =  data[offset+3];

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

            if (alpha == 0)
            {
                // Here is tap out of text
            }
            else
            {
                // Here is tap right into text
            }
        }

        UIGraphicsEndImageContext();
    }