我正在尝试创建一个自定义图像视图,接受一个点数组并一个接一个地在图像上绘制它们(不是一次全部)
我做了以下实现,一次性绘制所有圈子.
public class CustomImageView extends ImageView { private static final int RADIUS = 20; private Listpoints = new ArrayList<>(); private Paint paint; public CustomImageView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setColor(Color.RED); points.add(new Point(100, 100)); points.add(new Point(200, 200)); points.add(new Point(300, 300)); points.add(new Point(400, 400)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!points.isEmpty()) { for (int i = 0; i < points.size(); i++) { Point point = points.get(i); canvas.drawCircle(point.x, point.y, RADIUS, paint); } } } }
如何以一个小延迟一个接一个地在图像上绘制上述虚拟点?
这是一种用a做的方法ValueAnimator
.
要记住的一点是,onDraw()
可以随时为很多不同的原因被调用,所以你希望有一些状态,告诉你如何绘制的事情做好现在.在我们的例子中,它将是mNumCirclesToDraw
.该状态始终处于检入状态onDraw()
.
让这个工作的下一部分是创建一个ValueAnimator
将在正确的时间更新此状态然后调用invalidate()
以强制重绘.
这是一个例子:
public class CustomImageView extends ImageView implements ValueAnimator.AnimatorUpdateListener { private static final int RADIUS = 20; private Listpoints = new ArrayList<>(); private Paint paint; private ValueAnimator mValueAnimator; private int mNumCirclesToDraw = 0; public CustomImageView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setColor(Color.RED); points.add(new Point(100, 100)); points.add(new Point(200, 200)); points.add(new Point(300, 300)); points.add(new Point(400, 400)); setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mValueAnimator = ValueAnimator.ofInt(0, points.size()); mValueAnimator.setDuration(500 * points.size()); mValueAnimator.setInterpolator(new LinearInterpolator()); mValueAnimator.addUpdateListener(CustomImageView.this); mValueAnimator.start(); } }); } @Override public void onAnimationUpdate(ValueAnimator animation) { int val = (Integer) animation.getAnimatedValue(); if (val != mNumCirclesToDraw) { mNumCirclesToDraw = val; invalidate(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!points.isEmpty()) { for (int i = 0; i < mNumCirclesToDraw; i++) { Point point = points.get(i); canvas.drawCircle(point.x, point.y, RADIUS, paint); } } } }
在您的项目中试试这个.单击CustomImageView
以启动动画.