CABasicAnimation笔画结束动画百分比



我有一个基于字符计数的自定义进度视图。(类似twitter)

然而,我的计算似乎是错误的。我想让描边图层根据百分比来圆。

下面是我的代码:

class CharacterCountView: UIView {
private let progressLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func animateToValue(value: Double) {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.toValue = value
animation.duration = 0.5
animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
progressLayer.add(animation, forKey: "strokeAnimation")
progressLayer.strokeEnd = value

if value > 1 {
print("100% REACHED")
}
}
}
extension CharacterCountView {
fileprivate func setUpView() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(animateToValue)))
let trackLayer = CAShapeLayer()
trackLayer.frame = bounds
let path = UIBezierPath(arcCenter: trackLayer.position, radius: 8, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = path.cgPath
trackLayer.strokeColor = UIColor.systemGray2.cgColor
trackLayer.lineWidth = 1.5
trackLayer.fillColor = Color.background.cgColor
trackLayer.lineCap = .round
layer.addSublayer(trackLayer)
progressLayer.frame = bounds
progressLayer.path = path.cgPath
progressLayer.strokeColor = Color.accent.cgColor
progressLayer.lineWidth = 1.5
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .round
progressLayer.strokeEnd = 0
layer.addSublayer(progressLayer)
}
}

In my Text Did Change函数:

func textDidChange(to value: String) {
if value.isEmpty || value.count > 280 {
postBarButtonItem.isEnabled = false
} else {
postBarButtonItem.isEnabled = true
}

let characterCount = Double(value.count)
let percentage = characterCount / 280
print(percentage)
createPostInputAccessoryView.characterCountView.animateToValue(value: percentage)
}

它的峰值在70%左右,我的计算有问题吗?

您的endAngle是错误的…

让它更"可读"一点:

let path = UIBezierPath(arcCenter: trackLayer.position,
radius: 8,
startAngle: -CGFloat.pi / 2,
endAngle: 2 * CGFloat.pi,
clockwise: true)

这:startAngle: -CGFloat.pi / 2是负90度,或圆的12点钟方向。

但是这个:endAngle: 2 * CGFloat.pi是360度,或3点钟方向

所以你有450度而不是360度。

我发现只使用乘数有帮助,而不是将乘法和除法混合使用:

let path = UIBezierPath(arcCenter: trackLayer.position,
radius: 8,
startAngle: -CGFloat.pi * 0.5,
endAngle: CGFloat.pi * 1.5,
clockwise: true)

现在我们知道我们从零下90度到270度…查看360度全景

最新更新