title: How to convert UIImage/CGImageRef's alpha channel to mask?
body: <p>How can I extract the alpha channel of a UIImage or CGImageRef and convert it into a mask that I can use with CGImageMaskCreate?</p>
  
  <p>For example:</p>
  
  <p><img src="https://i.stack.imgur.com/Lmk1E.png" alt="example image"></p>
  
  <p>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. </p>
  
  <p>An example behavior of this is in the UIBarButtonItem when you supply it an icon image. According to the Apple docs it states:</p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>The UIBarButtonItem takes any image and looks only at the alpha, not the colors of the image.</p>