在自定义视图中执行路径动画

时间:2014-10-20 01:19:56

标签: java android ondraw invalidation

所以我有一个自定义视图,我尝试使用moveto()和lineto()的Path方法执行绘图动画。我有一个Point数组,我迭代并在每次迭代时调用invalidate()。在onDraw中,使用drawPath()绘制路径。当然,在循环完成之前不会调用onDraw。我相信我需要在后台线程中执行迭代。但与此同时,我已经读到在后台线程中执行UI更改是不好的做法。我怎样才能在每次迭代中重绘?

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPaint(mBackgroundPaint);
    canvas.drawPath(mPath, mStrokePaint);
}

public void drawPoints(){

    mPath = new Path();
    for (Stroke stroke : mStrokes){

        mDuration = stroke.getStrokeDuration();
        mInitialX = stroke.getInitialX();
        mInitialY = stroke.getInitialY();
        mPath.moveTo(mInitialX, mInitialY);
        invalidate();

        mPoints = new ArrayList<Point>();
        mPoints = stroke.getStrokePoints();
        int s = mPoints.size();

        long delayTime = mDuration / (long) s;


        for(Point point : mPoints){
            mX = point.getX();
            mY = point.getY();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPath.lineTo(mX, mY);
                    // want to call invalidate to redraw canvas
                    invalidate(); 
                }
            }, delayTime);


        }

    }








}

1 个答案:

答案 0 :(得分:0)

我有同样的问题,把它放到你的onDraw:

((Main) context).runOnUiThread(new Runnable() {
    @Override
    public void run() {
        CustomView.this.invalidate();

    }
});