我想用 colored颜色 参考对图像进行着色.结果看起来应该类似于Photoshop中的倍增混合模式,其中whites将替换为tint:

ALT Text

我将不断更改 colored颜色 值.

Follow up:我会将执行此操作的代码放在ImageView的drawRect:方法中,对吗?

和往常一样,code snippet分对我的理解有很大帮助,而不是链接.

Update:使用建议的代码Ramin将UIImageView子类化.

我把它放在我的视图控制器的viewDidLoad:中:

[self.lena setImage:[UIImage imageNamed:kImageName]];
[self.lena setOverlayColor:[UIColor blueColor]];
[super viewDidLoad];

我看到了这张照片,但没有着色.我还try 加载其他图像,在IB中设置图像,并在我的视图控制器中调用setNeedsDisplay:.

Update:drawRect:未被调用.

Final update:我发现了一个老项目,它有一个正确设置的imageView,这样我就可以测试Ramin的代码,它工作起来非常棒!

Final, final update:

对于那些刚刚学习Core Graphics的人来说,这里有一个可能可行的最简单的方法.

在您的子类UIView中:

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); // don't make color too saturated

    CGContextFillRect(context, rect); // draw base

    [[UIImage imageNamed:@"someImage.png"] drawInRect: rect blendMode:kCGBlendModeOverlay alpha:1.0]; // draw image
}

推荐答案

首先,您需要子类UIImageView并重写DrawRect方法.您的类需要一个UIColor属性(我们称其为overlayColor)来保存混合色,以及一个在 colored颜色 更改时强制重绘的自定义设置器.大概是这样的:

- (void) setOverlayColor:(UIColor *)newColor {
   if (overlayColor)
     [overlayColor release];

   overlayColor = [newColor retain];
   [self setNeedsDisplay]; // fires off drawRect each time color changes
}

在draRect方法中,您需要先绘制图像,然后使用一个矩形覆盖它,该矩形填充了所需的 colored颜色 以及正确的混合模式,如下所示:

- (void) drawRect:(CGRect)area
{
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSaveGState(context);

  // Draw picture first
  //
  CGContextDrawImage(context, self.frame, self.image.CGImage);

  // Blend mode could be any of CGBlendMode values. Now draw filled rectangle
  // over top of image.
  //
  CGContextSetBlendMode (context, kCGBlendModeMultiply);
  CGContextSetFillColor(context, CGColorGetComponents(self.overlayColor.CGColor));      
  CGContextFillRect (context, self.bounds);
  CGContextRestoreGState(context);
}

通常,为了优化绘图,您会将实际绘图限制为仅传递给drawRect的区域,但由于每次 colored颜色 更改时都必须重新绘制背景图像,因此整个图形可能需要刷新.

要使用它,请创建该对象的一个实例,然后将image属性(继承自UIImageView)设置为图片,将overlayColor设置为UICColor值(可以通过更改向下传递的 colored颜色 的Alpha值来调整混合级别).

Ios相关问答推荐

OSLog(Logger)通过简单的字符串插值给出错误

在TVOS中访问SWIFT中的objc++函数时发送给类的无法识别的 Select 符

在滚动视图中固定页眉,但在页眉上方嵌入元素

为什么EKEventStore().questFullAccessToEvents()可以与模拟器一起使用,而不能与真实设备一起使用?

在flutter中使用flatter_screenutil这样的软件包的目的是什么?

如何创建装饰视图?

SwiftUI HStack 文本字段对齐

如何根据条件快速将返回类型设为 LinearGradient 或 AngularGradient?

如何从 Locale Swift 获取货币符号

SwiftUI withAnimation 在视图出现之前不会启动

SwiftUI 中的偏移量和按钮有问题吗?

SwiftUI 切换语句

在 Swift 中合并子数组

ios 崩溃 EXC_BAD_ACCESS KERN_INVALID_ADDRESS

在 UITextView 中垂直居中文本

在代码生成的 UIView 上绘制 UIBezierPath

在 Swift 中上传带参数的图像

SwiftUI NavigationView navigationBarTitle LayoutConstraints 问题

自动布局:是什么创建了名为 UIView-Encapsulated-Layout-Width & Height 的约束?

如果我的分发证书过期会怎样?