2

我正在尝试在运行时更改图像的颜色。我在 SO 上看到了几个答案,但它们都改变了背景颜色而不是前景,这就是我想要做的。我的代码基于另一个SO 线程

这是我的代码:

@implementation UIImage (Coloring)

-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
    //create context
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // drawingcode
    //bg
    CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);

    [self drawInRect:rect];

    //fg
    CGContextSetBlendMode(context, kCGBlendModeMultiply);

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);

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

    //end
    return image;
}

@end

这是迄今为止的结果:

带有来自模拟器的三个快照的图片

从左到右:

  1. 没有混合,只是正常的资产。灰色背景来自UIViewimageviews的后面,图像的背景是透明的。
  2. 乘以kCGBlendModeMultiply
  3. 颜色燃烧与kCGBlendModeColorBurn

有没有CGBlendMode可以实现替换前景色的方法?另外,是否可以同时替换前景色(白色)和阴影(黑色)?

4

1 回答 1

3

在弄乱了不同的混合选项之后,这段代码成功了。唯一需要注意的是,红色色调显示在阴影中,它在技术上并不正确,但它接近 enuf

@implementation UIImage (Coloring)

-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
//create context
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();

//drawingcode
//bg
CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);

[self drawInRect:rect];

//fg
CGContextSetBlendMode(context, kCGBlendModeMultiply);

CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);

//mask
[self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0];

//end
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}
于 2013-08-02T01:52:21.447 回答