将渐变应用于UIImage

时间:2018-12-15 07:05:22

标签: ios swift uiimageview uiimage cagradientlayer

我想将颜色渐变(从上到下)应用于名为“ newspaperImage”的图像。这是我使用快速语言编写的代码。

@IBOutlet weak var newspaperImage: UIImageView!

func imageGradient(){
    let newspaperview = UIView(frame: newspaperImage.frame)
    let gradient = CAGradientLayer()
    gradient.frame = newspaperview.bounds
    let startColor = UIColor(red: 30, green: 113, blue: 79, alpha: 0).cgColor
    let endColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
    gradient.colors = [startColor, endColor]
    newspaperview.layer.insertSublayer(gradient, at: 0)
    newspaperImage.addSubview(newspaperview)
    newspaperImage.bringSubviewToFront(newspaperview)
}

override func viewDidLoad() {
    super.viewDidLoad()

    imageGradient()
}

运行后,我发现它根本不起作用。问题出在哪里?

1 个答案:

答案 0 :(得分:1)

首先让我们以UIColor(red:green:blue:alpha)开始,期望参数的标准化值为0-1。

所以...

let startColor = UIColor(red: 30, green: 113, blue: 79, alpha: 0).cgColor

应该是

let startColor = UIColor(red: 30/255, green: 113/255, blue: 79/255, alpha: 0).cgColor

接下来,我将您的基本代码放到Playground

let image = UIImage(named: "Miho_Small.png")

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
imageView.contentMode = .scaleAspectFit
imageView.image = image

let gradient = CAGradientLayer()
gradient.frame = imageView.bounds
let startColor = UIColor(red: 30/255, green: 113/255, blue: 79/255, alpha: 0).cgColor
let endColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
gradient.colors = [startColor, endColor]
imageView.layer.insertSublayer(gradient, at: 0)

imageView

它产生了...

Surprise

好吧,这不是我所期望的,但这并不完全令人惊讶。 CALayer被绘制在图像上方,因为图像是通过UIView的{​​{1}}函数绘制的。

好的,那么我们如何解决呢?不用再制作新图像并在其中绘制渐变和图像了,您可以使用“背景” draw,在其上应用图层和UIView

UIImageView

会生成...

Better

而且,可能更像是您想达到的目标……猜测

  

:(,两个视图不能重叠

我不会“重叠”,可以这么说,我将let image = UIImage(named: "Miho_Small.png") let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) imageView.contentMode = .scaleAspectFit imageView.image = image imageView.backgroundColor = nil let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) let gradient = CAGradientLayer() gradient.frame = backgroundView.bounds let startColor = UIColor(red: 30/255, green: 113/255, blue: 79/255, alpha: 0).cgColor let endColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor gradient.colors = [startColor, endColor] backgroundView.layer.insertSublayer(gradient, at: 0) backgroundView.addSubview(imageView) backgroundView 添加到包含UIImageView的{​​{1}}上。请记住,视图的backgroundView是相对于其父级坐标空间的。

在几乎所有情况下,我都喜欢使用自动布局,并且我喜欢使用故事板,但是这些很难解释,因此在本示例中我已经手工完成了...

Example

CALayer

关于它的价值,您可以从GitHub - TestCALayerGradientAndImageOverlay检出我用来测试代码的项目