3

I've got a UIImage which is generated as a screenshot. I'm adding this object with the following code:

self.view.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.0];
    drawImage.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.0];

    UIGraphicsBeginImageContext(self.view.bounds.size);
    [drawImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef rawImageRef=viewImage.CGImage;
    const float colorMasking[6] = {255,255,255,255,0,0}; 
    CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
    UIImage *newImage = [UIImage imageWithCGImage:rawImageRef];

However my Image only turns white, and I'd like to have the image to be transparent on the places where it's white by using CGImageCreateMaskingColors.

Hope someone can help me out.

BarryK88
  • 1,806
  • 2
  • 25
  • 41

1 Answers1

7
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 1.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef rawImageRef = viewImage.CGImage;
const float colorMasking[6] = {255, 255, 255, 255, 255, 255};
UIGraphicsBeginImageContext(viewImage.size);
CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, viewImage.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);

CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, viewImage.size.width, viewImage.size.height), maskedImageRef);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
CGImageRelease(maskedImageRef);
UIGraphicsEndImageContext();
tommyli
  • 131
  • 6
  • Your function works, however I have a very blurry result at the edges. – BarryK88 Feb 27 '12 at 21:53
  • I'm not sure about what costs the blurry result. Can you post the resultant image here? Maybe you can try to adjust the colorMasking, e.g. {225, 255, 225, 255, 225, 255}. – tommyli Feb 28 '12 at 02:26
  • turns out that when saving an image of a transparant view to the documentsdirectory my background turned white. So it could be that the blurry effect around the edges is caused by this. – BarryK88 Feb 29 '12 at 09:46
  • If your edge is blurry, try on the `UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, viewImage.image.scale);` – bubuxu May 11 '15 at 03:00