CAGradientLayer自动旋转

时间:2019-01-27 11:54:02

标签: ios uiview uiviewcontroller uikit cagradientlayer

我使用CAGradientLayer生成此细线渐变。问题是自转不顺畅。随着UIViewController旋转,我在viewDidLayoutSubviews中设置了包含该层的视图的框架,然后重置了该层的框架。当我自动旋转时,线条的高度会增加,并且渐变会在一段时间内从上到下渐变。自动旋转此图层的正确方法是什么?

enter image description here

1 个答案:

答案 0 :(得分:1)

我建议您放弃调整viewDidLayoutSubviews中的子层的工作。取而代之的是,我会让自动版式为您完成。

  • 首先,定义将呈现GradientView的{​​{1}}:

    CAGradientLayer

    通过指定此子视图的layerClass,您不必担心调整大小的问题。根据需要调整视图的大小,图层将相应地自动调整大小。

  • 然后,只需为新视图添加约束,然后让自动布局负责配置。例如

    class GradientView: UIView {
        // specify that the base layer should be gradient layer
    
        override class var layerClass: AnyClass {
            return CAGradientLayer.self
        }
    
        // it can be convenient to have computed property that returns layer of the `layerClass`
    
        private var gradientLayer: CAGradientLayer {
            return layer as! CAGradientLayer
        }
    
        // when we update our array of colors, update the gradient layer accordingly
    
        var colors: [UIColor] = [] {
            didSet {
                gradientLayer.colors = colors.map { $0.cgColor }
            }
        }
    
        // initializers
    
        override init(frame: CGRect = .zero) {
            super.init(frame: frame)
            configure()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            configure()
        }
    
        // configure the view for horizontal gradient
    
        private func configure() {
            colors = [.red, .yellow, .green, .blue]
            gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        }
    }
    

现在,显然,可以使用对您有用的任何约束,但是希望这可以说明这个想法。让自动布局配置视图的let gradientView = GradientView() gradientView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(gradientView) NSLayoutConstraint.activate([ gradientView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10), gradientView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10), gradientView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10), gradientView.heightAnchor.constraint(equalToConstant: 3) ]) ,并由于framelayerClass,它将自动为您更新。