Vanita L.
Vanita L.

Reputation: 1325

Change UIImage color without using Uiimageview in swift3

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

Upvotes: 0

Views: 476

Answers (2)

Vanita L.
Vanita L.

Reputation: 1325

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

Upvotes: 1

曾祥林
曾祥林

Reputation: 96

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.

Upvotes: 0

Related Questions