在 Android 上动画画布路径的绘制 [英] Animating the drawing of a canvas path on Android

查看:34
本文介绍了在 Android 上动画画布路径的绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动画路径的绘制,即让它逐渐出现在屏幕上.我正在使用画布,到目前为止我最好的猜测是使用 ObjectAnimator 来处理动画.但是,我无法弄清楚如何在 onDraw() 方法中实际绘制路径的相应段.有没有一种方法可以做到这一点?我需要为此考虑路径效应吗?

I'd like to animate the drawing of a path, i.e. to have it progressively appear on the screen. I am using the canvas and my best guess so far is to use an ObjectAnimator to take care of the animation. However, I cannot figure out how to actually draw the corresponding segment of the path in the onDraw() method. Is there a method that would allow to do this? Would I need to involve path effects for that?

使用 DashPathEffect 并在动画中设置其开"和关"间隔以覆盖我们要为该步骤绘制的路径部分似乎在这里工作,但它需要为动画的每一步分配一个新的 DashPathEffect.如果有更好的方法,我会留下这个问题.

Using a DashPathEffect and setting its "on" and "off" intervals in the animation to cover the part of the path we want to draw for that step seems to work here, but it requires allocating a new DashPathEffect for every step of the animation. I will leave the question open in case there is a better way.

推荐答案

回答我自己的问题,因为我想出了一个令人满意的方法.

Answering my own question, as I figured out a satisfying way to do that.

诀窍是使用 ObjectAnimator 来逐步改变当前笔画的长度,并使用 DashPathEffect 来控制当前笔画的长度.DashPathEffect 的 dashes 参数初始设置如下:

The trick is to use an ObjectAnimator to progressively change the current length of the stroke, and a DashPathEffect to control the length of the current stroke. The DashPathEffect will have its dashes parameter initially set to the following:

float[] dashes = { 0.0f, Float.MAX_VALUE };

第一个浮点数是可见笔画的长度,第二个是不可见部分的长度.选择的第二长度非常高.因此,初始设置对应于完全不可见的笔画.

First float is the length of the visible stroke, second length of non-visible part. Second length is chosen to be extremely high. Initial settings thus correspond to a totally invisible stroke.

然后每次对象动画师更新笔画长度值时,都会使用新的可见部分创建一个新的DashPathEffect并设置为Painter对象,并且视图失效:

Then everytime the object animator updates the stroke length value, a new DashPathEffect is created with the new visible part and set to the Painter object, and the view is invalidated:

dashes[0] = newValue;
mPaint.setPathEffect(new DashPathEffect(dashes, 0));
invalidate();

最后,onDraw() 方法使用这个画家来绘制路径,它只会包含我们想要的部分:

Finally, the onDraw() method uses this painter to draw the path, which will only comprise the portion we want:

canvas.drawPath(path, mPaint);

我看到的唯一缺点是我们必须在每个动画步骤中创建一个新的 DashPathEffect(因为它们不能重复使用),但总体来说这是令人满意的 - 动画很好而且很流畅.

The only drawback I see is that we must create a new DashPathEffect at every animation step (as they cannot be reused), but globally this is satisfying - the animation is nice and smooth.

这篇关于在 Android 上动画画布路径的绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆