I want draw image pattern like star, one can change the color for that. Can I change the color of Image itself without using image view? I saw many answer changing tint color of UIImageview, but the effect is not applied to UIImage
Asked
Active
Viewed 453 times
0
-
Can you provide some code of what you are trying to do – Casper Zandbergen Apr 07 '17 at 07:55
-
1Possible duplicate of [How to apply a tintColor to a UIImage?](http://stackoverflow.com/questions/19802982/how-to-apply-a-tintcolor-to-a-uiimage) – inokey Apr 07 '17 at 08:08
-
Found the solution posted below – Van Apr 07 '17 at 11:39
-
@Van if anyone get solution from stack overflow or already have question then mark duplicate – Nazmul Hasan Apr 07 '17 at 11:47
2 Answers
1
Thank you all for the answers, but I got the solution working.
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()
}
The patternImage is the the image added in asset. P.S. the patternImage added in asset SHOULD be in black color

Van
- 1,225
- 10
- 18
0
tintColor
is not only a property of a UIImageView
, it is a property of a UIView
, as long as your image is in a UIView, you can use UIView.tintColor
.

曾祥林
- 96
- 4
-
I want to add the effect to image not image view, as I will draw pattern in context, thanks – Van Apr 07 '17 at 11:41