如何解决如何快速根据圆圈中的百分比填充笔触颜色
我正在创建一个圆圈并分成四个部分。笔触颜色应根据给定的百分比填充。
func showCircle() {
dispatchQueue.main.asyncAfter(deadline: dispatchTime.Now()+0.2) { [weak self] in
guard let `self` = self else { return }
self.layer.cornerRadius = self.frame.size.width / 2
self.backgroundColor = .clear
let total: Int = 4
let width: CGFloat = 10.0
let reducer: CGFloat = 0.0 // add gape b/w segments if reducer > 0
let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width / 2,y: self.frame.size.height / 2),radius: self.frame.size.width / 2,startAngle: CGFloat(-0.5 * Double.pi),endAngle: CGFloat(1.5 * Double.pi),clockwise: true)
// these are the percentages
let percentages = [0.20,0.15,0.35,0.30]
for i in 1...total {
let percentage = CGFloat(percentages[i - 1] )
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
switch i-1 {
case 0:
circleShape.strokeColor = #colorLiteral(red: 0.431372549,green: 0.231372549,blue: 0.631372549,alpha: 1)
case 1:
circleShape.strokeColor = #colorLiteral(red: 0.6784313725,green: 0.568627451,blue: 0.7882352941,alpha: 1)
case 2:
circleShape.strokeColor = #colorLiteral(red: 0.8470588235,green: 0.7960784314,blue: 0.8980392157,alpha: 1)
case 3:
circleShape.strokeColor = #colorLiteral(red: 0.9490196078,green: 0.937254902,blue: 0.9568627451,alpha: 1)
default:
circleShape.strokeColor = #colorLiteral(red: 0,green: 0,blue: 0,alpha: 1)
}
circleShape.fillColor = UIColor.clear.cgColor
circleShape.linewidth = width
circleShape.strokeStart = CGFloat(CGFloat(i - 1) * percentage) + reducer
circleShape.strokeEnd = CGFloat(CGFloat(i) * percentage) - reducer
self.layer.addSublayer(circleShape)
}
}
}
错误的结果:- 这些颜色应根据百分比填充。
预期结果:- 我们可以在这张图片中看到颜色根据百分比正确填充。
解决方法
你的错误是strokeStart和strokeEnd应该从0到1并且随着索引的增加而增加。
这是行得通的:
// these are the percentages
let percentages = [0.20,0.15,0.35,0.30]
for i in 1...total {
let prevPercentage: Double = percentages.prefix(i - 1).reduce(0,+)
let percentage = percentages[i - 1]
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
switch i-1 {
case 0:
circleShape.strokeColor = UIColor.red.cgColor
case 1:
circleShape.strokeColor = UIColor.green.cgColor
case 2:
circleShape.strokeColor = UIColor.blue.cgColor
case 3:
circleShape.strokeColor = UIColor.orange.cgColor
default:
circleShape.strokeColor = #colorLiteral(red: 0,green: 0,blue: 0,alpha: 1)
}
circleShape.fillColor = UIColor.clear.cgColor
circleShape.lineWidth = width
circleShape.strokeStart = CGFloat(prevPercentage)
circleShape.strokeEnd = CGFloat(prevPercentage + percentage)
view.layer.addSublayer(circleShape)
}
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。