我想要像星星一样绘制图像模式,可以改变颜色。我可以在不使用图像视图的情况下更改图像本身的颜色吗?我看到很多回答改变UIImageview的色调,但效果不适用于UIImage
答案 0 :(得分:1)
谢谢大家的答案,但我得到了解决方案。
func changePatternImageColor() {
patternImage = UIImage(named: "pattern_star.png")! //make sure to reinitialize the original image here every time you change the color
UIGraphicsBeginImageContext(patternImage.size)
let context = UIGraphicsGetCurrentContext()
let color = UIColor(red: self.red, green: self.green, blue: self.blue, alpha: self.opacity)
color.setFill()
context?.translateBy(x: 0, y: patternImage.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
//set the blend mode to color burn, and the original image
context?.setBlendMode(CGBlendMode.exclusion) //this does the magic.
let rect = CGRect(x: 0, y: 0, width: patternImage.size.height, height: patternImage.size.height)
context?.draw(patternImage.cgImage!, in: rect)
//set the mask that matches the shape of the image, then draw color burn a colored rectangle
context?.clip(to: rect, mask: patternImage.cgImage!)
context?.addRect(rect)
context?.drawPath(using: CGPathDrawingMode.fill)
patternImage = UIGraphicsGetImageFromCurrentImageContext()!
image_ref = patternImage.cgImage
UIGraphicsEndImageContext()
}
patternImage是资产中添加的图像。 附:资产应该中添加的patternImage为黑色
答案 1 :(得分:0)
tintColor
不仅是UIImageView
的属性,而且是UIView
的属性,只要您的图片位于UIView中,就可以使用UIView.tintColor
}。