我想使用CAShapeLayer
制作一个循环指标。我在自定义类中执行此操作,因此我可以为每个UIView
重复使用它。
这就是我现在所拥有的:
class CircularIndicator: UIView {
var circularIndicator = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure() {
let centerPoint = CGPoint(x: self.bounds.width / 2, y: self.bounds.width / 2)
let circleRadius = self.bounds.size.width / 2
let circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)
circularIndicator.path = circlePath.cgPath
circularIndicator.strokeColor = UIColor.blue.cgColor
circularIndicator.fillColor = UIColor.clear.cgColor
circularIndicator.lineWidth = 6
circularIndicator.strokeStart = 0
circularIndicator.strokeEnd = 1
self.layer.addSublayer(circularIndicator)
}
}
我在主视图控制器中添加了UIView
,其高度和宽度= 150.我的问题是,当我运行应用时,circleRadius
值最终为500,这使得圆圈方式大。
我的理解是self.bounds.witdh
或self.bounds.height
应该等于包含此类的UIView
的值。
我错了吗?为什么我的宽度和高度值如此之大?
答案 0 :(得分:3)
问题是Data newD = d.withField<int, &Data::field2>(4);
可能会发生变化。因此,您应在frame
中设置path
:
layoutSubviews
顺便说一句,您可能希望将圆圈插入class CircularIndicator: UIView {
var circularIndicator = CAShapeLayer()
var lineWidth: CGFloat = 6
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
circularIndicator.strokeColor = UIColor.blue.cgColor
circularIndicator.fillColor = UIColor.clear.cgColor
circularIndicator.lineWidth = lineWidth
circularIndicator.strokeStart = 0
circularIndicator.strokeEnd = 1
layer.addSublayer(circularIndicator)
}
override func layoutSubviews() {
super.layoutSubviews()
let centerPoint = CGPoint(x: bounds.width / 2, y: bounds.width / 2)
let circleRadius = (bounds.size.width - lineWidth) / 2
circularIndicator.path = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true).cgPath
}
}
的一半,如上所示,我会相应地调整lineWidth
。否则,圆的边缘将超过视图的circleRadius
。