在 swift3 中不使用 Uiimageview 更改 UIImage 颜色
Change UIImage color without using Uiimageview in swift3
我想画星星这样的图案,可以改变颜色。我可以在不使用图像视图的情况下更改图像本身的颜色吗?我看到很多答案改变了 UIImageview 的色调,但效果不适用于 UIImage
tintColor
不仅是 UIImageView
的 属性,它还是 UIView
的 属性,只要你的图片在一个 UIView,你可以使用 UIView.tintColor
.
谢谢大家的回答,但我得到了解决方案。
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是asset中添加的图片。
P.S。添加到资产中的图案图像 应该 是黑色
我想画星星这样的图案,可以改变颜色。我可以在不使用图像视图的情况下更改图像本身的颜色吗?我看到很多答案改变了 UIImageview 的色调,但效果不适用于 UIImage
tintColor
不仅是 UIImageView
的 属性,它还是 UIView
的 属性,只要你的图片在一个 UIView,你可以使用 UIView.tintColor
.
谢谢大家的回答,但我得到了解决方案。
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是asset中添加的图片。 P.S。添加到资产中的图案图像 应该 是黑色