Hello everyone I need help with my iOS app. How can I get the background color of the image (that I insert in UIImageView) exactly where I tap. I create a Tap Gesture Recognizer but I do not know how to read the background color where I tap.
Asked
Active
Viewed 211 times
-1
-
1You don't mean background colour, you mean just the colour, right? At the pixel which the user tapped? – Pekka Jul 29 '15 at 13:12
-
1Googling `ios tapped image pixel color` seems to yield a lot of hits – Pekka Jul 29 '15 at 13:13
-
e.g. http://stackoverflow.com/questions/9270923/how-to-read-rgb-pixel-data-on-iphone – Pekka Jul 29 '15 at 13:13
-
http://stackoverflow.com/questions/3284185/get-pixel-color-of-uiimage – Pekka Jul 29 '15 at 13:14
-
http://stackoverflow.com/questions/144250/how-to-get-the-rgb-values-for-a-pixel-on-an-image-on-the-iphone – Teja Nandamuri Jul 29 '15 at 13:14
-
I'll leave it to the tag experts to determine which is the best duplicate – Pekka Jul 29 '15 at 13:14
-
Yes, sorry. I need the color of the pixel where I press. – Neoxxx Jul 29 '15 at 13:15
-
I read this: http://stackoverflow.com/questions/3284185/get-pixel-color-of-uiimage but the latest code don't work... – Neoxxx Jul 29 '15 at 13:16
1 Answers
5
add gesture in your control
UITapGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
[lblSlider addGestureRecognizer:tapRecognizer];
lblSlider.userInteractionEnabled = YES;
after add this method
- (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();
}

Ankit Kargathra
- 309
- 3
- 16
-
-
-
Nothing. Error: cannot initialize a variable of type 'unsigned char *' with an r value of type 'void *' – Neoxxx Jul 29 '15 at 13:53
-