如何为进度视图制作动画?

时间:2018-08-09 06:27:26

标签: ios swift xcode bar-chart

我正在使用https://github.com/gordoneliel/LinearProgressBar。我想制作动画。

这是实现绘图方法的代码的一部分:

    func drawProgressView() {
    guard let context = UIGraphicsGetCurrentContext() else {return}

    let beginPoint = CGPoint(x: barPadding + trackOffset, y: frame.size.height / 2)


    // Progress Bar Track
    drawOn(
        context: context,
        lineWidth: barThickness + trackPadding,
        begin: beginPoint,
        end: CGPoint(x: frame.size.width - barPadding - trackOffset, y: frame.size.height / 2),
        lineCap: .round,
        strokeColor: trackColor
    )

    // Progress bar
    let colorForBar = barColorForValue?(Float(progressValue)) ?? barColor

    drawOn(
        context: context,
        lineWidth: barThickness,
        begin: beginPoint,
        end: CGPoint(x: barPadding + trackOffset + calculatePercentage(), y: frame.size.height / 2),
        lineCap: .round,
        strokeColor: colorForBar
    )
}

是否可以在此处添加动画?

我找到了如何将其添加到进度视图:self.progressView.setProgress(1.0,animation:true)。但我想将其添加到https://github.com/gordoneliel/LinearProgressBar

1 个答案:

答案 0 :(得分:0)

由于您正在处理图层,因此可以尝试CATransaction。

您可以将图层重绘包含在这样的动画块中

UIView.transition(with: myView, duration: 1, options: .transitionCrossDissolve, animations: {
myView.layer.displayIfNeeded()
})

或者尝试将您的drawOn封闭在CATransaction事务中

CATransaction.begin()
CATransaction.setAnimationDuration(0.25)
drawOn(
    context: context,
    lineWidth: barThickness,
    begin: beginPoint,
    end: CGPoint(x: barPadding + trackOffset + calculatePercentage(), y: frame.size.height / 2),
    lineCap: .round,
    strokeColor: colorForBar
)
CATransaction.commit()

希望这会有所帮助。