ios - 如何在swift中根据圆圈中的百分比填充笔触颜色
问题描述
我正在创建一个圆圈并分为四个部分。描边颜色应根据给定的百分比填充。
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)
}
结果:
推荐阅读
- javascript - 将变量从一个函数传递到另一个函数
- python - 有没有办法随机打乱 Python 字典中的键和值,但结果不能有任何原始键值对?
- javascript - 如何在更改原点的 chrome-extension 中使用 fetch?
- object - 在数组对象类中找不到方法的符号
- sql - 当一列为空时,使用 db2 中的另一列
- python - UTC 时间戳转换为日期时间返回意外日期
- node.js - 一种逐一检查集合中所有数据的有效方法(nodejs、mongoose)
- c - 如何将文件的内容存储到数组中 (C)
- python - 即使使用参数也无法写入 SQL Server
- javascript - 未定义的处理程序?