How can I extract the alpha channel of a UIImage or CGImageRef and convert it into a mask that I can use with CGImageMaskCreate?
For example:

Essentially, given any image, I don’t care about the colors inside the image. All I want is to create a grayscale image that represents the alpha channel. This image can then be used to mask other images.
An example behavior of this is in the UIBarButtonItem when you supply it an icon image. According to the Apple docs it states:
The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored.
The UIBarButtonItem takes any image and looks only at the alpha, not the colors of the image.
To color icons the way the bar button items do, you don’t want the traditional mask, you want the inverse of a mask– one where the opaque pixels in the original image take on your final coloring, rather than the other way around.
Here’s one way to accomplish this. Take your original RBGA image, and process it by:
E.g.
Now you can use
finalMaskImageas the mask inCGContextClipToMasketc, or etc.