gpt4 book ai didi

swift - 具有线性渐变的饼图 - swift

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

我知道这个问题已经出现好几次了。我试图实现我案例的所有答案,但我仍然不知道该怎么做。

我有一种饼图,我想为每个部分创建渐变,例如中心为绿色,远离中心(或其他所有...)则更红。但我要么面临占据所有屏幕的渐变(看起来我还不明白裁剪上下文的工作原理),要么我什么也没看到。

override func draw(_ rect: CGRect)
{
let centerX = (bounds.size.width)/2
let centerY = (bounds.size.height)/2
let center = CGPoint(x: centerX, y: centerY)
let radius: (CGFloat) = min(centerX/2, centerY/2)
let context = UIGraphicsGetCurrentContext()

// A method where I configure labels
func label(text: String, value: CGFloat, angle: CGFloat, color: UIColor) {

let labX = centerX + cos(angle) * newValue * 1.2
let labY = centerY + sin(angle) * newValue * 1.2
let myLabel = UILabel(frame: CGRect(x: labX, y: labY, width: 80, height: 40))

...
addSubview(myLabel)
}

// Configure arc -> where I try to add gradients to my segments
func arc(radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat) {

var finalRadius: CGFloat = radius
if radius == -1 {
finalRadius = 100
phenotypeColor = UIColor.init(red: 159/255.0, green: 193/255.0, blue: 204/255.0, alpha: 0.5)
}
else {
phenotypeColor = UIColor.orange
}

context?.setFillColor(phenotypeColor.cgColor)
context?.move(to: center)
context?.addArc(center: center, radius: finalRadius, startAngle: startAngle, endAngle: edAngle, clockwise: true)
context?.fillPath()

// I would like to implement here a gradient layer to the newly-created arc. I tried o add a CAGradientLayer but I cannot apply it to the segment area...
}

// One arc
label(text: ..., value: ..., angle: ..., color: ...)
arc(radius: ..., startAngle: ..., endAngle: ...)

//Another arc
...


}

如果有人能帮助我...

这只是我没有任何渐变的图像: enter image description here

编辑:我尝试在下面添加这些行,但没有成功。

    let path = UIBezierPath(arcCenter: center, radius: finalRadius, startAngle: myStartAngle, endAngle: myEndAngle, clockwise: true)
let RectView = path.bounds
let myView = UIView.init(frame: RectView)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = myView.bounds
gradientLayer.colors = [UIColor.red, UIColor.blue]
myView.layer.addSublayer(gradientLayer)

谁能告诉我如何从路径获取 UIView?

最佳答案

这里需要一个 CAGradientLayer。

let gradientLayer = CAGradientLayer()
gradientLayer.frame = myView.bounds
gradientLayer.colors = [UIColor.red, UIColor.blue]
myView.layer.addSublayer(gradientLayer)

其中 myView 是具有饼图段的 View 。

如果您有任何进一步的问题,请告诉我,我希望您能使它正常工作 - 看起来很酷 :)

关于swift - 具有线性渐变的饼图 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768255/

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