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

自定义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,想想刚才真是脑子进水了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程