我知道这个问题已经存在了相当几次。我试图实现我的案件的所有答案,但我仍然无法弄清楚如何做到这一点。饼图与线性渐变 - 迅速
我有一种饼图,我想为每一个段上创建渐变,例如绿色的中心,更红,因为它从中心消失(或一切......)。但我无论是面对一个渐变,通吃屏幕(它看起来像我不明白如何裁剪上下文作品)或我什么也没看到。
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
...
}
如果有人可以帮助我...
编辑: 我尝试下面添加这些行没有任何成功。
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?
谢谢回答! Thath或多或少是我之前尝试过的,但我不确定如何让“myView”成为一个细分的视图。我想这可能要涉及到“裁剪”上下文功能或其他任何东西,但我不能做它,因为我用的是.move,.addArc和.fillPath方法获得成功。 – Trichophyton