如何使用Swift渐变填充自定义UIView?

时间:2018-01-12 23:35:45

标签: ios swift custom-view

我有一个自定义三角形UIView,我想用自定义渐变颜色填充。

override func draw(_ rect: CGRect) {

    let widerStartingPoint = CGFloat(240)

    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.beginPath()
    context.move(to: CGPoint(x: rect.minX - widerStartingPoint, y: rect.maxY))
    context.addLine(to: CGPoint(x: rect.maxX + widerStartingPoint, y: rect.maxY))
    context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY))
    context.closePath()

    let colors = [firstColor.cgColor, secondColor.cgColor ,thirdColor.cgColor] as CFArray

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let colorLocations: [CGFloat] = [0.0, 0.5 ,1.0]

    let startPoint = CGPoint.zero
    let endPoint = CGPoint(x: 0, y: bounds.height)

    let gradient = CGGradient(colorsSpace: colorSpace,
                              colors: colors as CFArray,
                              locations: colorLocations)!

    // I need to find a way to change below color with gradient color
    context.setFillColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 0.60)
    context.fillPath()
}

我试图找到其他setFillColor方法,但它们只允许分配单一颜色。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

我使用setFillColor而不是使用context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: []),而是在路径中添加了剪辑。所以工作代码在下面!:

override func draw(_ rect: CGRect) {

    let widerStartingPoint = CGFloat(240)

    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.beginPath()
    context.move(to: CGPoint(x: rect.minX - widerStartingPoint, y: rect.maxY))
    context.addLine(to: CGPoint(x: rect.maxX + widerStartingPoint, y: rect.maxY))
    context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY))
    context.closePath()

    // This was missing!
    context.clip()

    let colors = [firstColor.cgColor, secondColor.cgColor ,thirdColor.cgColor] as CFArray

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let colorLocations: [CGFloat] = [0.0, 0.5 ,1.0]

    let startPoint = CGPoint.zero
    let endPoint = CGPoint(x: 0, y: bounds.height)

    let gradient = CGGradient(colorsSpace: colorSpace,
                              colors: colors as CFArray,
                              locations: colorLocations)!

    // Also used this method
    context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
    context.fillPath()
}