Manually drawing a gradient in iPhone apps?

后端 未结 7 1433
一个人的身影
一个人的身影 2020-12-28 20:53

If I have two UIColors, what\'s the best way to draw an even gradient between them over an arbitrarily-sized area?

I am guessing you would create a UIView subclass a

7条回答
  •  死守一世寂寞
    2020-12-28 21:26

    Same-ish solution as @Anton Chikin but a little more robust. Notice the override of layerClass... this way, you don't have to worry about setting the frame and the frame is automatically updated upon rotation & resize.

    class GradientView: UIView {
    
        var colorA : UIColor = UIColor.greenColor() {
            didSet { updateGradient() }
        }
        var colorB : UIColor = UIColor.blueColor() {
            didSet { updateGradient() }
        }
    
        override class func layerClass() -> AnyClass {
            return CAGradientLayer.self
        }
    
        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            updateGradient()
        }
    
        func updateGradient() {
            if let gLayer = layer as? CAGradientLayer {
                gLayer.colors = [colorA.CGColor, colorB.CGColor]
            }
        }
    
    }
    

    If you're using IB, you can set the properties via "User Defined Runtime Attributes".

    If you're not using IB, use the other initializer.

提交回复
热议问题