xcode 如何以编程方式在 Swift 中的图像上添加渐变层?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29633205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I programmatically add a Gradient Layer over an image in Swift?
提问by Hugo Alonso
I want to place a layer with a predefined Transparent to Blackgradient on top of an UIImage whose content image is loaded via web and creating an effect of a shadow over it.
我想在UIImage 顶部放置一个具有预定义透明到黑色渐变的图层,该图层的内容图像通过网络加载并在其上创建阴影效果。
I don't want to do it via loading a png with such a gradient.
我不想通过加载具有这种渐变的 png 来做到这一点。
回答by Duncan C
I suggest creating a custom subclass of UIView (or UIImageView, if what you want to add the gradient to is a UIImageView). In the init method of your custom view, create a CAGradientLayer and add it as a sublayer of your view's layer. Then set up the black to transparent gradient on the layer.
我建议创建一个自定义的 UIView 子类(或 UIImageView,如果你想添加渐变的是 UIImageView)。在自定义视图的 init 方法中,创建一个 CAGradientLayer 并将其添加为视图层的子层。然后在图层上设置黑色到透明的渐变。
You will probably need to override layoutSubviews() and change the settings on your gradient layer in case the view's bounds change.
您可能需要覆盖 layoutSubviews() 并更改渐变层上的设置,以防视图的边界发生变化。
EDIT:
编辑:
I created a playground as a gist on githubthat is a working example of this:
我在 github 上创建了一个操场作为要点,这是一个工作示例:
The code looks like this:
代码如下所示:
import UIKit
import AVFoundation
class ImageViewWithGradient: UIImageView
{
let myGradientLayer: CAGradientLayer
override init(frame: CGRect)
{
myGradientLayer = CAGradientLayer()
super.init(frame: frame)
self.setup()
}
required init(coder aDecoder: NSCoder)
{
myGradientLayer = CAGradientLayer()
super.init(coder: aDecoder)
self.setup()
}
func setup()
{
myGradientLayer.startPoint = CGPoint(x: 0, y: 0)
myGradientLayer.endPoint = CGPoint(x: 1, y: 1)
let colors: [CGColorRef] = [
UIColor.clearColor().CGColor,
UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor,
UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).CGColor,
UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor,
UIColor.clearColor().CGColor ]
myGradientLayer.colors = colors
myGradientLayer.opaque = false
myGradientLayer.locations = [0.0, 0.3, 0.5, 0.7, 1.0]
self.layer.addSublayer(myGradientLayer)
}
override func layoutSubviews()
{
myGradientLayer.frame = self.layer.bounds
}
}
var aView = ImageViewWithGradient(frame: CGRect(x: 0, y: 0, width: 500, height: 500))