Reputation: 1806
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.
Upvotes: 3
Views: 5805
Reputation: 131
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();
Upvotes: 7