如何使一种颜色在UIImage上透明?

在我的iPhone应用程序上,我有一个UIImage实例。我想获得一个派生的UIImage,它是第一个UIImage的结果,其中第一个UIImage的颜色(例如洋红色)变为透明。我怎样才能做到这一点?



拉丁的传说
浏览 706回答 3
3回答

慕侠2389804

-(void)changeColor{    UIImage *temp23=[UIImage imageNamed:@"leaf.png"];    CGImageRef ref1=[self createMask:temp23];    const float colorMasking[6] = {1.0, 2.0, 1.0, 1.0, 1.0, 1.0};    CGImageRef New=CGImageCreateWithMaskingColors(ref1, colorMasking);    UIImage *resultedimage=[UIImage imageWithCGImage:New];}-(CGImageRef)createMask:(UIImage*)temp{    CGImageRef ref=temp.CGImage;    int mWidth=CGImageGetWidth(ref);    int mHeight=CGImageGetHeight(ref);    int count=mWidth*mHeight*4;    void *bufferdata=malloc(count);    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;    CGContextRef cgctx = CGBitmapContextCreate (bufferdata,mWidth,mHeight, 8,mWidth*4, colorSpaceRef, kCGImageAlphaPremultipliedFirst);     CGRect rect = {0,0,mWidth,mHeight};    CGContextDrawImage(cgctx, rect, ref);     bufferdata = CGBitmapContextGetData (cgctx);    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bufferdata, mWidth*mHeight*4, NULL);    CGImageRef savedimageref = CGImageCreate(mWidth,mHeight, 8, 32, mWidth*4, colorSpaceRef, bitmapInfo,provider , NULL, NO, renderingIntent);    CFRelease(colorSpaceRef);    return savedimageref;}   以上代码经过测试,我通过使用遮罩将绿色更改为红色

潇湘沐

这是yubenyi的代码的一项调整,可以多次使用。通过将图像转换为未压缩的jpeg,它将在处理之前剥离alpha通道。还添加了一些有关颜色范围选择如何工作的注释。-(UIImage *)changeWhiteColorTransparent: (UIImage *)image{    //convert to uncompressed jpg to remove any alpha channels    //this is a necessary first step when processing images that already have transparency    image = [UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)];    CGImageRef rawImageRef=image.CGImage;    //RGB color range to mask (make transparent)  R-Low, R-High, G-Low, G-High, B-Low, B-High    const double colorMasking[6] = {222, 255, 222, 255, 222, 255};    UIGraphicsBeginImageContext(image.size);    CGImageRef maskedImageRef=CGImageCreateWithMaskingColors(rawImageRef, colorMasking);    //iPhone translation    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);     CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();    CGImageRelease(maskedImageRef);    UIGraphicsEndImageContext();        return result;}
打开App,查看更多内容
随时随地看视频慕课网APP