ios - UIImage 覆盖颜色 : bad result

标签 ios uiimage core-graphics

我需要用纯色覆盖一个小的 png。 我使用的代码是:

- (UIImage *)overlayWithColor:(UIColor *)overlayColor {


    UIGraphicsBeginImageContext(self.size);

    CGContextRef context = UIGraphicsGetCurrentContext();


    [overlayColor setFill];

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

    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextDrawImage(context, rect, self.CGImage);


    CGContextClipToMask(context, rect, self.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

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

    return coloredImg;

}

但结果不是很平滑...这里是原始图像(黑色)和叠加图像(白色)

enter image description here enter image description here

最佳答案

我的做法如下(假设您是 iOS7-only): 反转原始图像:在 Photoshop 或类似工具中对其进行编辑,使黑线透明(alpha),而空白则不透明(它是什么颜色都无所谓,只要它不透明即可)。 然后在代码中:

imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[imageView.image setTintColor:[UIColor orangeColor]];

其中 imageView 是包含您的图像的 View 。

关于ios - UIImage 覆盖颜色 : bad result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723496/

相关文章:

ios - 如果本地文档中没有图片,则下载图片

cocoa - 用CGImage绘制图像?

ios - 如何绘制带有一个或多个 100% 半透明圆圈的 UIImage 矩形?

ios - 从时区获取当前时间,而不是系统/移动时间

ios - Xamarin iOS 如何使用相同的 ViewController 为 iPad 和 iPhone 制作不同的 xib

ios - 为什么我在 iOS 6 中切换 tabBar Items 数组时出现黑屏?

ios - 结构添加 $(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH) 不起作用

iphone - MFMessageViewController 和内联 UIImage

ios - 如何垂直平铺 UIImage 而仅在 iOS 上水平拉伸(stretch)?

iphone - 创建线条时 CGContextFillPath(context) 被删除