【问题标题】:Android: animate the alpha of single Path on a canvasAndroid:在画布上为单个路径的 alpha 设置动画
【发布时间】:2011-06-06 22:00:20
【问题描述】:

我想在 android 画布上为单个路径设置动画。

public class MyView extends View {
    private Path paths[];
    protected void onDraw( Canvas canvas ) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth( 8 );
        paint.setColor(Color.BLUE);

        Path path = new Path();
        path.moveTo(75, 11);
        path.quadTo(62, 87, 10, 144);
        canvas.drawPath( path, paint );
        paths[0] = path;

        path.reset();
        path.moveTo(50, 100);
        path.lineTo(150, 200);
        canvas.drawPath( path, paint );
        paths[1] = path;
    }
}

现在我有了路径[],我想分别为每一个设置动画。我希望它像增长一样改变 alpha。一开始只有一个小点,然后长成一条线,重复。

可以吗?

怎么做?

【问题讨论】:

标签: android animation canvas path


【解决方案1】:

我会添加一个从 0 到 1 的新浮点数,以保持当前动画百分比并使用它来设置当前 alpha

public class MyView extends View {
     private Path paths[];
     private float mAnimPercentage = 0.0f;

    private static final int clip(int value){  //forces the value to be between 0 and 255
        return Math.max(0, Math.min(255, value));
    }
    protected void onDraw( Canvas canvas ) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth( 8 );
        paint.setColor(Color.BLUE);

        Path path = new Path();
        path.moveTo(75, 11);
        path.quadTo(62, 87, 10, 144);
        //edited here
        paint.setAlpha(clip(mAnimPercentage*255*2));
        canvas.drawPath( path, paint );
        paths[0] = path;

        path.reset();
        path.moveTo(50, 100);
        path.lineTo(150, 200);
        //edited here
        paint.setAlpha(clip(-127 + mAnimPercentage*255*2));   //the biggest is the negative value, the latter this path will show, the biggest is the number multiplied by mAnimPercentage, the fastest this path will get completely opaque
        canvas.drawPath( path, paint );
        paths[1] = path;
        mAnimPercentage+= 0.01; //FIXME this is for TEST only, you should update it with an animator
        postInvalidate();
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2012-03-27
    • 1970-01-01
    • 2020-11-02
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多