iphony
iphony

Reputation:

How to obtain UIColor from a UIImage on iPhone

I want to process my image point by point, but I don't know how to obtain the color of the point from the image. And how to move the pointer point by point?

Upvotes: 3

Views: 4843

Answers (2)

Greg Carpenter
Greg Carpenter

Reputation: 11

to hopefully save someone a lot of time, the CreateARGBBitmapContext function should have a memset(bitmapData, 0, bitmapByteCount); after the malloc success so you don't get random data in the source image - that will set everything to effectively transparent.

Upvotes: 1

philsquared
philsquared

Reputation: 22493

You can't do it directly from the UIImage, but you can render the image into a bitmap context, with a memory buffer you supply, then test the memory directly. That sounds more complex than it really is, but may still be more complex than you wanted to hear.

If you have Erica Sadun's iPhone Developer's Cookbook there's good coverage of it from page 54. I'd recommend the book overall, so worth getting that if you don't have it.

I arrived at almost exactly the same code independently, but hit one bug that it looks like may be in Sadun's code too. In the pointInside method the point and size values are floats and are multiplied together as floats before being cast to an int. This is fine if your coordinates are discreet values, but in my case I was supplying sub-pixel values, so the formula broke down. The fix is easy once you've identified the problem, of course - just cast each coordinate to an int before multiplying - so, in Sadun's case it would be:


long startByte = ((int)point.y * (int)size.width) + (int)point.x) * 4;

Also, Sadun's code, as well as my own, are only interested in alpha values, so we use 8 bit pixels that take the alpha value only. Changing the CGBitMapContextCreate call should allow you to get actual colour values too (obviously if you have more than 8 bits per pixel you will have to multiply that in to your pointInside formula too).

[edit] This prompted me to put the code up on my blog (with a side-track while I worked out how to syntax highlight it):

Upvotes: 3

Related Questions