使用UIColor填充UIImage
我有一个UIImage
,我想用UIColor
填充
我试过这段代码,但应用程序在第10行崩溃了。
这是代码:
extension UIImage { func imageWithColor(_ color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0.0, y: size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(origin: CGPoint.zero, size: size) context?.clip(to: rect, mask: context as! CGImage)// crashes color.setFill() context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() return newImage! } }
问题可能在于context?.clip(to: rect, mask: context as! CGImage)
(我想我不应该发送context
作为掩码,但是我应该发送什么? CGImage()
和CGImage.self
‘工作。
完成绘图后,您需要结束图像上下文:
UIGraphicsEndImageContext();
或者你可以为UIImage添加一个类别方法:
- (UIImage *)imageByTintColor:(UIColor *)color { UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); [color set]; UIRectFill(rect); [self drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeDestinationIn alpha:1]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
用作:
image = [image imageByTintColor:color];
你必须做如下:
extension UIImage { func tinted(with color: UIColor) -> UIImage? { defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(size, false, scale) color.set() withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size)) return UIGraphicsGetImageFromCurrentImageContext() } }
最简单的方法
theImageView.image? = (theImageView.image?.imageWithRenderingMode(.AlwaysTemplate))! theImageView.tintColor = UIColor.magentaColor()
let image = UIImage(named: "whatever.png")?.imageWithRenderingMode(.alwaysTemplate)
当您稍后将此图像设置为UIButton或UIImageView时 – 只需更改该控件的色调,并使用您指定的色调颜色绘制图像。