views:

278

answers:

1

I've tried some code from each of these questions:

How to make one color transparent on a UIImage?

How to mask a UIImage so that white becomes transparent on iphone?

but have come up unsuccessful, unfortunately working with Core Graphics and images is not my strong suit.

How would I go about accessing a UIImage's raw data and changing the white pixels to clear?

Thanks!

+1  A: 

How would I go about accessing a UIImage's raw data …?

Look at the documentation.

You'll find that there is no way to get the raw data behind a UIImage. The closest you can get is a CGImage. That will let you get its data provider, which you can ask for a copy of the raw data.

The problem with that solution is that you need to handle every possible configuration (RGBA, ARGB, RGB_, _RGB, RGB, 8-bpc, 16-bpc, etc.) that CGImage supports. That's a lot of work. If you don't do it, then someday, you'll get surprised by an image that somehow doesn't work with your code, or by an OS upgrade changing how the CGImage gets created.

The CGImageCreateWithMaskingColors function, suggested on one of the other questions you linked to, is the correct solution.

One thing that's tripping you up is that the values shown in the accepted answer on that question are generally bogus: They're out of range. The Quartz 2D Programming Guide has more details in at least two.places.

I also argue against including that answer's createMask: method, since it doesn't do what it says it does and is barely useful at all (it's only worth having if the source image may be CMYK, but how likely is that on an iPhone app?). Skip it and create the mask image from the UIImage's CGImage directly.

That answer will probably work just fine once you fix those two problems.

Peter Hosey