【问题标题】:Change UIImage color without using Uiimageview in swift3在 swift3 中不使用 Uiimageview 更改 UIImage 颜色
【发布时间】:2023-03-16 19:26:01
【问题描述】:

我想画出像星星一样的图案,可以改变颜色。我可以在不使用图像视图的情况下更改图像本身的颜色吗?我看到很多答案改变了 UIImageview 的 tint color,但效果不适用于 UIImage

【问题讨论】:

  • 你能提供一些你正在尝试做的代码吗
  • 找到下面发布的解决方案
  • @Van 如果有人从堆栈溢出中获得解决方案或已经有问题,则标记重复

标签: swift uiimage uicolor


【解决方案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 是添加到asset 中的图片。 附言在资产中添加的 patternImage 应该为黑色

【讨论】:

    【解决方案2】:

    tintColor不仅是UIImageView的属性,还是UIView的属性,只要你的图片在UIView中,就可以使用UIView.tintColor

    【讨论】:

    • 我想将效果添加到图像而不是图像视图,因为我将在上下文中绘制图案,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2018-08-20
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多