为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉丁的传说 2019-11-26 10:28:57
在我的iPhone应用程序上,我有一个UIImage实例。我想获得一个派生的UIImage,它是第一个UIImage的结果,其中第一个UIImage的颜色(例如洋红色)变为透明。我怎样才能做到这一点?
查看完整描述

3 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

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

}   

以上代码经过测试,我通过使用遮罩将绿色更改为红色


查看完整回答
反对 回复 2019-11-26
?
潇湘沐

TA贡献1816条经验 获得超6个赞

这是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;

}


查看完整回答
反对 回复 2019-11-26
  • 3 回答
  • 0 关注
  • 699 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信