我知道可以通过在矩形图像上绘制CGContextFillRect并设置混合模式来对其进行着色。但是,我不知道如何在透明图像上进行着色。这必须是可能的,因为SDK在这样的标签栏上做它自己。有人能提供一个代码片段吗?
更新:
自从我最初提出这个问题以来,已经给出了很多很好的建议。一定要通读所有的答案,找出最适合你的。
更新(2015年4月30日):
有了iOS 7.0,我现在可以做以下事情,这将满足我最初问题的需要。但是,如果您有更复杂的情况,请查看所有答案。
UIImage *iconImage = [[UIImage imageNamed:@"myImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *icon = [[UIImageView alloc] initWithImage:iconImage];
icon.tintColor = [UIColor redColor];
发布于 2014-03-20 17:21:37
我使用这种方法最成功,因为我尝试过的其他方法会导致某些颜色组合的半透明像素的颜色失真。这在性能方面也应该更好一些。
+ (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;
}
发布于 2010-08-20 02:13:35
经过搜索,到目前为止,我得到的最好的解决方案是使用混合模式和剪切蒙版的组合来实现透明PNG的着色/着色:
CGContextSetBlendMode (context, kCGBlendModeMultiply);
CGContextDrawImage(context, rect, myIconImage.CGImage);
CGContextClipToMask(context, rect, myIconImage.CGImage);
CGContextSetFillColorWithColor(context, tintColor);
CGContextFillRect(context, rect);
发布于 2013-09-26 18:46:03
您可以创建一个UIImage类别,如下所示:
- (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;
}
https://stackoverflow.com/questions/3514066
复制相似问题