Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

iphone - How can I change the color 'white' from a UIImage to transparent

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...