gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:05:55 30 4
gpt4 key购买 nike

我有一个自定义三角形 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 方法,但它们只允许分配单一颜色。

感谢您的宝贵时间。

最佳答案

我没有使用 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()
}

关于ios - 如何使用 Swift 渐变填充自定义 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48235463/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com