【问题标题】:How can I create a template image to be colored at run time如何创建要在运行时着色的模板图像
【发布时间】:2013-09-23 05:49:01
【问题描述】:

我有一张几乎是纯色的图像。它已连接,但纯白色,因此您无法轻易看到。

我希望能够在运行时动态地为这个图像着色,但我需要在 iOS 6 中做到这一点,而不使用 UIImageRenderingModeAlwaysTemplate。

图像都将从纯白色开始,圆角带有较小的渐变。

到目前为止,我最好的尝试是使用 GPUImage 和 UIImage 上的一个类别

@implementation UIImage (BPAdditions)

- (UIImage *)imageWithColor:(UIColor *)color
{

    GPUImageRGBFilter *stillImageFilter = [[GPUImageRGBFilter alloc] init];
    CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    stillImageFilter.red = red;
    stillImageFilter.green = green;
    stillImageFilter.blue = blue;
    GPUImageChromaKeyFilter *stillImageFilter2 = [[GPUImageChromaKeyFilter alloc] init];
    [stillImageFilter2 setColorToReplaceRed:0 green:0 blue:0];
    stillImageFilter2.thresholdSensitivity = 0.2;
    stillImageFilter2.smoothing = 0;
    UIImage *img = [stillImageFilter imageByFilteringImage:self];

    return [stillImageFilter2 imageByFilteringImage: img];
}

这将是理想的,除非当我使用 RGB 滤镜时,它会将清晰的背景变成黑色。然后使用色度过滤器将其移除,其质量会因所使用的颜色而异。

目标颜色有可能是黑色,在这种情况下,此解决方案将完全失败。

【问题讨论】:

  • 图片相当简单。在UIView 中将其创建为UIBezierPath 并在drawRect 中呈现它会不会更容易。这样你就可以很容易地控制它的颜色。您可以使用 PaintCode 查找路径的代码。
  • 是否有令人信服的理由为现有位图应用颜色,而不是仅仅添加带有适当颜色/渐变/圆角的UIView
  • 它将以这种方式使用应用程序中的所有资产,其中一些并不那么简单,需要我做大量的工作来构建。我的预期方式意味着我可以让我们的设计师构建图像,我可以为它们着色以用于单独的配色方案。

标签: ios objective-c image-processing uiimage gpuimage


【解决方案1】:

不确定我是否理解您想要实现的目标,但您想在基本图像中添加简单的色调吗?如果是这样,您可以通过 UIImage 上的以下类别来实现:

- (UIImage *)tintWithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGRect drawRect = CGRectMake(0, 0, self.size.width, self.size.height);
    [self drawInRect:drawRect];
    [tintColor set];
    UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceAtop);
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

-- 更新:Swift 2 版本--

extension UIImage {

    func tintWithColor(color:UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height)
        self.drawInRect(rect)
        color.setFill()
        UIRectFillUsingBlendMode(rect, CGBlendMode.SourceAtop)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }

}

【讨论】:

  • 正是我想要的,完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多