首页 文章

在swift3中不使用Uiimageview更改UIImage颜色

提问于
浏览
0

我想要像星星一样绘制图像模式,可以改变颜色 . 我可以在不使用图像视图的情况下更改图像本身的颜色吗?我看到许多回答改变UIImageview的色调,但效果不适用于UIImage

2 回答

  • 0

    tintColor 不仅是 UIImageView 的属性,它是 UIView 的属性,只要您的图像在UIView中,就可以使用 UIView.tintColor .

  • 0

    谢谢大家的答案,但我得到了解决方案 .

    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是资产中添加的图像 . 附:在资产 SHOULD 中添加的patternImage为黑色

相关问题