首页 > 解决方案 > 如何使用 UIImage 作为蒙版将渐变应用到 UIImageView

问题描述

我有一个UIImage里面的UIImageView。我想以UIImage.

我可以将 渲染UIImage为模板并对 应用着色UIImageView,但显然它只有一种颜色而不是渐变。我在这里看到了一些关于使用它UIImage作为面具的东西,但我无法弄清楚。有人知道怎么做吗?

标签: iosswift

解决方案


可能有更简单的方法,但如果我做对了,这可能对你有用:

// create image and image view
let image = UIImage(named: "yourImage")
let imageView = UIImageView(image: image)

// create the gradient
let gradient = CAGradientLayer()
gradient.colors = [
    UIColor.red.cgColor,
    UIColor.green.cgColor
]
gradient.startPoint = CGPoint(x: 1, y: 0.5)
gradient.endPoint = CGPoint(x: 0, y: 0.5)
gradient.frame = imageView.bounds

// add a mask to the gradient
let mask = CALayer()
mask.contents = image?.cgImage
mask.frame = gradient.bounds

gradient.mask = mask

// add the gradient as a sublayer to the image view's layer
imageView.layer.addSublayer(gradient)

结果:

结果


推荐阅读