views:

389

answers:

3

I am trying to develop a small application. In it, I need to detect the color of a pixel within an UIView. I have a CGPoint defining the pixel I need. The colors of the UIView are changed using CoreAnimation.

I know there are some complex ways to extract color information from UIImages. However I couldn't find a solution for UIViews.

In Pseudo-Code I am looking for something like

pixel = [view getPixelAtPoint:myPoint];
UIColor *mycolor = [pixel getColor];

Any input greatly appreciated.

+3  A: 

It is pretty horrible and slow. Basically you great a bitmap context with a backing store you allocate so you can read the memory, then you render the views layer in the context and read the appropriate point in ram.

If you know how to do it for an image already you can do something like this:

- (UIImage *)imageForView:(UIView *)view {
  UIGraphicsBeginImageContext(view.frame.size);
  [view.layer renderInContext: UIGraphicsGetCurrentContext()];
  UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
  UIGraphicsEndImageContext();

  return retval;
}

to get an image then get the pixel out. I am sure the mechanism you have for dealing with images involves rendering them into a context anyway, so you can merge that with this and factor out the actual image creation. So if you take that could and remove the bit where you load the image and replace it with the context render:

[view.layer renderInContext: UIGraphicsGetCurrentContext()];

you should be good.

Louis Gerbarg
A: 

Fixed some minor errors

- (UIImage *)imageForView:(UIView *)view {
    UIGraphicsBeginImageContext(view.frame.size);
    [view.layer renderInContext: UIGraphicsGetCurrentContext()];
    UIImage *retval = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return retval;
}

Also, add

#import <QuartzCore/QuartzCore.h>

to your file to avoid warning messages.

Combining your code with the code found here works flawlessly.

0x90
Why does it look like you simply copied Louis's code and removed the superfluous "void" in the call to `UIGraphicsGetImageFromCurrentImageContext()`?
Kevin Ballard
That is what I did. What is a better way to handle corrections on here?
0x90
A: 

Hi, I want to know the pixel color inside a uiview, basically i rendered pie in view and now i want to know the pixel color where i am tapping inside pie view, here the solution what you gave is for image, is there any other way to get the tap event on pie chart that shows which slice i touched or to get the pixelcolor at point i touched. In both of the cases i will get my answer.

Naren