leen_wei
2019-04-18 15:52
采纳率: 100%
浏览 463

自定义view使用动画的问题

最近在学习自定义view相关的东西,想实现一个画圆的动画,但是始终没有效果,代码如下:

public class AnimatorView extends View {
    private static final String TAG = "AnimatorView";

    private Paint mPaint;
    private RectF mArcRectF;
    private ObjectAnimator mProgressAnim;

    private int mProgress = 0;

    public AnimatorView(Context context) {
        this(context, null);
    }

    public AnimatorView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AnimatorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        initAnimator();
    }

    private void init() {
        if(mPaint == null)
            mPaint = new Paint();
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.RED);
        mPaint.setStrokeWidth(16);
    }

    private void initAnimator() {
        mProgressAnim = ObjectAnimator.ofInt(this, "progress", 0, 360);
        mProgressAnim.setDuration(5000);
        mProgressAnim.setInterpolator(null);
    }

    public int getProgress() {
        return mProgress;
    }

    public void setProgress(int progress) {
        mProgress = progress;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);  

        int centerX = width / 2;
        int centerY = height / 2;
        int offset = Math.min(centerX, centerY) / 2;

        mArcRectF = new RectF(centerX - offset, centerY - offset, centerX + offset, centerY + offset);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Log.d(TAG, "onDraw() ---> mProgress=" + mProgress);
        canvas.drawArc(mArcRectF, 90, mProgress, false, mPaint);
        mProgressAnim.start();
    }
}

我的想法是通过mProgress来逐渐的将圆弧扩大,但实际效果是这个值一直为0,这个属性动画还是没搞明白

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • leen_wei 2019-04-18 16:09
    已采纳

    唉,终于知道怎么回事了,原来是onDraw里面的 mProgressAnim.start();处理有问题,需要添加一个判断:
    if(!isAnimationRunning) {
    isAnimationRunning = true;
    mProgressAnim.start();
    }
    否则像上面这样就会陷入类似死循环,不停的调用start,想想刚才真是脑子进水了。

    打赏 评论

相关推荐 更多相似问题