title: iOS color to transparent in UIImage
body: <p>How can I clear out the magenta part of an UIImage and make it transparent?</p>
  
  <p>I've looked through numerous answers and links on SO and nothing works (e.g. <a href="https://stackoverflow.com/questions/633722/how-to-make-one-color-transparent-on-a-uiimage/1108300#1108300">How to make one color transparent on a UIImage?</a> answer 1 removes everything but red, answer 2 apparently doesn't work because of <a href="https://stackoverflow.com/questions/3563770/why-is-cgimagecreatewithmaskingcolors-returning-nil-in-this-case">Why is CGImageCreateWithMaskingColors() returning nil in this case?</a>).</p>
  
  <p><strong>Update:</strong></p>
  
  <p>If I use CGImageCreateWithMaskingColors with the UIImage I get a nil value. If I remove the alpha channel (I represent the image as JPEG and read it back) CGImageCreateWithMaskingColors returns an image painted with a black background.</p>
  
  <p><strong>Update2, the code:</strong></p>
  
  <p>Returning nil:</p>
  
  <pre><code>const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
  CGImageRef imageRef = CGImageCreateWithMaskingColors(anchorWithMask.CGImage, colorMasking);
  
  NSLog(@"image ref %@", imageRef);
  // this is going to return a nil imgref.
  
  UIImage *image = [UIImage imageWithCGImage:imageRef];
  </code></pre>
  
  <p>Returning an image with black background (which is normal since there is not alpha channel):</p>
  
  <pre><code>UIImage *inputImage = [UIImage imageWithData:UIImageJPEGRepresentation(anchorWithMask, 1.0)];
  
  const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
  CGImageRef imageRef = CGImageCreateWithMaskingColors(inputImage.CGImage, colorMasking);
  
  NSLog(@"image ref %@", imageRef);
  // imgref is NOT nil.
  
  UIImage *image = [UIImage imageWithCGImage:imageRef];
  </code></pre>
  
  <p><strong>Update3:</strong></p>
  
  <p>I got it working by adding the alpha channel after the masking process.</p>