有角度的梯度层

时间:2016-05-04 21:08:57

标签: swift uiview swift2 gradient cagradientlayer

我有自定义UIView类,它在Swift 2中呈现渐变。我正在努力制作一个有角度的渐变,以便从左上角到右下角绘制。有人可以帮我一点吗?

import UIKit

class GradientView: UIView {

    let gradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        // 1
        self.backgroundColor = ColorPalette.White

        // 2
        gradientLayer.frame = self.bounds

        // 3
        let color1 = ColorPalette.GrdTop.CGColor as CGColorRef
        let color2 = ColorPalette.GrdBottom.CGColor as CGColorRef
        gradientLayer.colors = [color1, color2]

        // 4
        gradientLayer.locations = [0.0, 1.0]

        // 5
        self.layer.addSublayer(gradientLayer)
    }

}

我怀疑这应该是别的东西,但无论我输入什么都没有变化。

gradientLayer.locations = [0.0, 1.0]

5 个答案:

答案 0 :(得分:21)

您不想使用locations指定渐变的方向。而是使用startPointendPoint

当想要在locationsstartPoint之间指定应该发生渐变的位置时,会使用endPoint数组。例如,如果您希望颜色仅在起点和终点范围的10%中间进行,则使用:

locations = [0.45, 0.55]

locations数组不指示方向。 startPointendPoint会这样做。因此,对于从左上角到右下角的对角线渐变,您可以将startPoint CGPoint(x: 0, y: 0)endPoint设置为CGPoint(x: 1, y: 1)

例如:

@IBDesignable
class GradientView: UIView {

    override class var layerClass: AnyClass { return CAGradientLayer.self }

    private var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }

    @IBInspectable var color1: UIColor = .white { didSet { updateColors() } }
    @IBInspectable var color2: UIColor = .blue  { didSet { updateColors() } }

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configureGradient()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureGradient()
    }

    private func configureGradient() {
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        updateColors()
    }

    private func updateColors() {
        gradientLayer.colors = [color1.cgColor, color2.cgColor]
    }

}

E.g。

enter image description here

注意,与直接问题无关:

  • 如果您要将渐变添加为子图层,则需要在frame中更新此子图层的layoutSubviews,以便在视图的bounds发生更改时, frame的{​​{1}}。但是,更好的是,覆盖视图的gradientLayer,它不仅会为您实例化layerClass,还会在视图大小发生变化时享受渐变的动态调整,特别是处理动画更优雅地改变。

  • 同样,我设置了CAGradientLayercolor1,这样它们就会触发渐变的更新,以便颜色的任何变化都会立即反映在视图中。

  • 我做了这个color2,所以如果我把它放在自己的框架中,然后在IB中添加@IBDesignable,我会看到在IB中呈现的效果。

对于Swift 2的实施,请参阅previous revision of this answer

答案 1 :(得分:5)

任意角度的渐变起点和终点

Swift 4.2,Xcode 10.0

鉴于任何角度,我的代码将设置渐变层的相应起点和终点。

如果输入的角度大于 360°,则除以 360 时将使用余数。

  • 输入 415°会产生与输入 55°
  • 相同的结果

如果输入的角度小于,则会逆时针旋转

  • 输入 -15°将产生与输入 345°
  • 相同的结果

代码:

public extension CAGradientLayer {

    /// Sets the start and end points on a gradient layer for a given angle.
    ///
    /// - Important:
    /// *0°* is a horizontal gradient from left to right.
    ///
    /// With a positive input, the rotational direction is clockwise.
    ///
    ///    * An input of *400°* will have the same output as an input of *40°*
    ///
    /// With a negative input, the rotational direction is clockwise.
    ///
    ///    * An input of *-15°* will have the same output as *345°*
    ///
    /// - Parameters:
    ///     - angle: The angle of the gradient.
    ///                  
    public func calculatePoints(for angle: CGFloat) {


        var ang = (-angle).truncatingRemainder(dividingBy: 360)

        if ang < 0 { ang = 360 + ang }

        let n: CGFloat = 0.5

        switch ang {

        case 0...45, 315...360:
            let a = CGPoint(x: 0, y: n * tanx(ang) + n)
            let b = CGPoint(x: 1, y: n * tanx(-ang) + n)
            startPoint = a
            endPoint = b

        case 45...135:
            let a = CGPoint(x: n * tanx(ang - 90) + n, y: 1)
            let b = CGPoint(x: n * tanx(-ang - 90) + n, y: 0)
            startPoint = a
            endPoint = b

        case 135...225:
            let a = CGPoint(x: 1, y: n * tanx(-ang) + n)
            let b = CGPoint(x: 0, y: n * tanx(ang) + n)
           startPoint = a
            endPoint = b

        case 225...315:
            let a = CGPoint(x: n * tanx(-ang - 90) + n, y: 0)
            let b = CGPoint(x: n * tanx(ang - 90) + n, y: 1)
            startPoint = a
            endPoint = b

        default:
            let a = CGPoint(x: 0, y: n)
            let b = CGPoint(x: 1, y: n)
            startPoint = a
            endPoint = b

        }
    }

    /// Private function to aid with the math when calculating the gradient angle
    private func tanx(_ : CGFloat) -> CGFloat {
        return tan( * CGFloat.pi / 180)
    }


    // Overloads

    /// Sets the start and end points on a gradient layer for a given angle.
    public func calculatePoints(for angle: Int) {
        calculatePoints(for: CGFloat(angle))
    }

    /// Sets the start and end points on a gradient layer for a given angle.
    public func calculatePoints(for angle: Float) {
        calculatePoints(for: CGFloat(angle))
    }

    /// Sets the start and end points on a gradient layer for a given angle.
    public func calculatePoints(for angle: Double) {
        calculatePoints(for: CGFloat(angle))
    }

}

用法:

let gradientLayer = CAGradientLayer()

// Setup gradient layer...

// Gradient Direction: →
gradient.calculatePoints(for: 0)

// Gradient Direction: ↗︎
gradient.calculatePoints(for: -45)

// Gradient Direction: ←
gradient.calculatePoints(for: 180)

// Gradient Direction: ↓
gradient.calculatePoints(for: 450)

数学解释

所以我实际上最近才花了很多时间自己回答这个问题。以下是一些示例角度,仅用于帮助理解和可视化顺时针旋转方向。

Example Angles

如果您对我的计算方式感兴趣,我制作了一张桌子,从本质上可视化了- 360°的工作。

Table

答案 2 :(得分:4)

您似乎忘了在startPoint上设置CAGradientLayer()。下面的代码是您提供的代码,以及我的补充。

import UIKit

class GradientView: UIView {

    let gradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        // 1
        self.backgroundColor = ColorPalette.White

        // 2
        gradientLayer.frame = self.bounds

        // 3
        let color1 = ColorPalette.GrdTop.CGColor as CGColorRef
        let color2 = ColorPalette.GrdBottom.CGColor as CGColorRef
        gradientLayer.colors = [color1, color2]

        //** This code should do the trick... **//
        gradientLayer.startPoint = CGPointMake(0.0, 0.5)

        // 4
        gradientLayer.locations = [0.0, 1.0]

        // 5
        self.layer.addSublayer(gradientLayer)
    }
}

答案 3 :(得分:3)

我不确定是什么让你无法工作,但我确实有一个我使用的GradientView可以是水平或垂直的,并且可以使用ui builder。随意使用它并根据您的需求进行改进:

import UIKit

@IBDesignable  class  GradientView: UIView {
    var gradient:CAGradientLayer
    @IBInspectable var startColor:UIColor = UIColor.whiteColor() {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var color1:UIColor? = nil {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var stop1:Double = (1.0 / 3.0) {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var color2:UIColor? = nil {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var stop2:Double = (2.0 / 3.0) {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var endColor:UIColor = UIColor.blackColor() {
        didSet {
            self.updateGradient()
        }
    }

    @IBInspectable var isHorizontal:Bool {
        get {
            return self.gradient.endPoint.y == self.gradient.startPoint.y
        }
        set {
            self.gradient.endPoint = newValue ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 1)
        }
    }

    override init(frame: CGRect) {
        gradient = CAGradientLayer()
        super.init(frame: frame)
        self.configGradient()
    }

    required init?(coder aDecoder: NSCoder) {
        gradient = CAGradientLayer()
        super.init(coder: aDecoder)
        self.configGradient()
    }

    func configGradient() {
        self.backgroundColor = UIColor.clearColor()
        self.layer.insertSublayer(self.gradient, atIndex: 0)
        self.gradient.masksToBounds = true
        self.gradient.frame = self.bounds
        self.gradient.startPoint = CGPoint(x: 0, y: 0)
        self.gradient.endPoint = CGPoint(x: 1, y: 0)
        self.updateGradient()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.gradient.frame = self.bounds
    }

    func updateGradient() {
        var colors:[CGColorRef] = []
        var locations:[NSNumber] = []
        colors.append(self.startColor.CGColor)
        locations.append(0.0.nsNumber)

        if let color = self.color1 {
            colors.append(color.CGColor)
            locations.append(self.stop1)}

        if let color = self.color2 {
            colors.append(color.CGColor)
            locations.append(self.stop2)
        }

        colors.append(self.endColor.CGColor)
        locations.append(1.0.nsNumber)

        self.gradient.colors = colors
        self.gradient.locations = locations

        self.layer.setNeedsDisplay()
    }
}

答案 4 :(得分:0)

可以使用一些基本的三角学来实现成角度的梯度。您可以通过对UIView进行子类化来实现它,如我在blog post on the subject中所述。

首先定义一些变量:-

// The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
var endPoint: CGPoint

// The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
var startPoint: CGPoint

// the gradient angle, in degrees anticlockwise from 0 (east/right)
@IBInspectable var angle: CGFloat = 270

下面的核心函数获取单位空间中的起点和终点。

// create vector pointing in direction of angle
private func gradientPointsForAngle(_ angle: CGFloat) -> (CGPoint, CGPoint) {
    // get vector start and end points
    let end = pointForAngle(angle)
    let start = oppositePoint(end)
    // convert to gradient space
    let p0 = transformToGradientSpace(start)
    let p1 = transformToGradientSpace(end)
    return (p0, p1)
}

这只是获取用户指定的角度,并使用它创建指向该方向的矢量。角度指定矢量从0度开始的旋转角度,按照惯例,该角度在Core Animation中指向东,然后逆时针(逆时针)增加。

相关代码的其余部分在下面,并且与所得到的点在单位圆上有关。但是,我们需要的点在单位平方中:将向量外推到单位平方。

private func pointForAngle(_ angle: CGFloat) -> CGPoint {
    // convert degrees to radians
    let radians = angle * .pi / 180.0
    var x = cos(radians)
    var y = sin(radians)
    // (x,y) is in terms unit circle. Extrapolate to unit square to get full vector length
    if (fabs(x) > fabs(y)) {
        // extrapolate x to unit length
        x = x > 0 ? 1 : -1
        y = x * tan(radians)
    } else {
        // extrapolate y to unit length
        y = y > 0 ? 1 : -1
        x = y / tan(radians)
    }
    return CGPoint(x: x, y: y)
}

private func oppositePoint(_ point: CGPoint) -> CGPoint {
    return CGPoint(x: -point.x, y: -point.y)
}

private func transformToGradientSpace(_ point: CGPoint) -> CGPoint {
    // input point is in signed unit space: (-1,-1) to (1,1)
    // convert to gradient space: (0,0) to (1,1), with flipped Y axis
    return CGPoint(x: (point.x + 1) * 0.5, y: 1.0 - (point.y + 1) * 0.5)
}

最终所有内容都必须从更新函数中调用:-

private func updateGradient() {
    if let gradient = self.gradient {
        let (start, end) = gradientPointsForAngle(self.angle)
        gradient.startPoint = start
        gradient.endPoint = end
        gradient.frame = self.bounds
    }
}

有关完整的实现,请参阅我的blog post