ios - 使用混合对图像着色/遮蔽前景

标签 ios uiimage core-graphics

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

这是我的代码:

@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

这是迄今为止的结果:

picture with three snapshots from the simulator

从左到右:

  1. 没有混合,只是普通资源。灰色背景来自imageviews后面的UIView,图像的背景是透明的。
  2. kCGBlendModeMultiply相乘
  3. 使用 kCGBlendModeColorBurn 进行颜色加深

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

最佳答案

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

@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;
}

关于ios - 使用混合对图像着色/遮蔽前景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18006520/

相关文章:

ios - Xcode 8.3 存档错误 : Linker command failed with exit code 1

ios - Air for iOS 中是否有使用 "GPU mode"作为渲染方法的快速渲染游戏库?

ios - 视频缩略图未出现在 Collection View 中

ios - 在 iOS 上创建动画指示器箭头

IOS:屏蔽图像以考虑视网膜比例因子

ios - 什么时候使用 NSURLProtocol?

ios - 如何根据商店为我的应用程序使用不同的名称

iphone - UIImageWriteToSavedPhotosAlbum 仅保存 10 张图像中的 5 张。为什么?

iphone - 如何模糊UIImage,但保留清晰的对象边界?

ios - CoreGraphics - 无法将 UnsafeMutablePointer<UInt32> 替换为 UnsafeMutablePointer<UInt8>