首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在iPhone中对透明的PNG图像进行着色?

如何在iPhone中对透明的PNG图像进行着色?
EN

Stack Overflow用户
提问于 2010-08-18 23:59:32
回答 9查看 41.8K关注 0票数 74

我知道可以通过在矩形图像上绘制CGContextFillRect并设置混合模式来对其进行着色。但是,我不知道如何在透明图像上进行着色。这必须是可能的,因为SDK在这样的标签栏上做它自己。有人能提供一个代码片段吗?

更新:

自从我最初提出这个问题以来,已经给出了很多很好的建议。一定要通读所有的答案,找出最适合你的。

更新(2015年4月30日):

有了iOS 7.0,我现在可以做以下事情,这将满足我最初问题的需要。但是,如果您有更复杂的情况,请查看所有答案。

代码语言:javascript
复制
UIImage *iconImage = [[UIImage imageNamed:@"myImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];    
UIImageView *icon = [[UIImageView alloc] initWithImage:iconImage];
icon.tintColor = [UIColor redColor];
EN

回答 9

Stack Overflow用户

发布于 2014-03-20 17:21:37

我使用这种方法最成功,因为我尝试过的其他方法会导致某些颜色组合的半透明像素的颜色失真。这在性能方面也应该更好一些。

代码语言:javascript
复制
+ (UIImage *) imageNamed:(NSString *) name withTintColor: (UIColor *) tintColor {

    UIImage *baseImage = [UIImage imageNamed:name];

    CGRect drawRect = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);

    UIGraphicsBeginImageContextWithOptions(baseImage.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0, baseImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    // draw original image
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextDrawImage(context, drawRect, baseImage.CGImage);

    // draw color atop
    CGContextSetFillColorWithColor(context, tintColor.CGColor);
    CGContextSetBlendMode(context, kCGBlendModeSourceAtop);
    CGContextFillRect(context, drawRect);

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return tintedImage;
}
票数 21
EN

Stack Overflow用户

发布于 2010-08-20 02:13:35

经过搜索,到目前为止,我得到的最好的解决方案是使用混合模式和剪切蒙版的组合来实现透明PNG的着色/着色:

代码语言:javascript
复制
CGContextSetBlendMode (context, kCGBlendModeMultiply);

CGContextDrawImage(context, rect, myIconImage.CGImage);

CGContextClipToMask(context, rect, myIconImage.CGImage);

CGContextSetFillColorWithColor(context, tintColor);

CGContextFillRect(context, rect);
票数 18
EN

Stack Overflow用户

发布于 2013-09-26 18:46:03

您可以创建一个UIImage类别,如下所示:

代码语言:javascript
复制
- (instancetype)tintedImageWithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = (CGRect){ CGPointZero, self.size };
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    [self drawInRect:rect];

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [tintColor setFill];
    CGContextFillRect(context, rect);

    UIImage *image  = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3514066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档