Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 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 Reply

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...