《Android---簡單的自定義加載控件及Xfermode的使用》

部分代碼

 @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        mCenterX = width / 2;
        mCenterY = height / 2;
        mRadius = Math.min(width / 2, height) / 2;

        mCircle1 = new PointF(mCenterX - mRadius, mCenterY);
        mCircle2 = new PointF(mCenterX + mRadius, mCenterY);

        ValueAnimator animator = ValueAnimator.ofFloat(0, 2, 4);
        animator.setDuration(2000);
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mAnimatorValue = (float) animation.getAnimatedValue();
            }
        });
//        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.saveLayer(0, 0, getWidth(), getHeight(), mPaint, Canvas.ALL_SAVE_FLAG);
        boolean isBack = false;
        float tmpValue = mAnimatorValue;
        if (tmpValue > 2) {
            tmpValue = 4 - mAnimatorValue;
            isBack = true;
        }

        float value = tmpValue;
        if (tmpValue > 1) {
            value = 2 - tmpValue;
        }

        int color1 = mColor1;
        int color2 = mColor2;
        float radius = mRadius - (mRadius / 3 * value);
        mPaint.setColor(color1);
        canvas.drawCircle(mCircle1.x + (mRadius * tmpValue), mCircle1.y, radius, mPaint);
        if (isBack) {
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        } else {
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
        }

        mPaint.setColor(color2);
        canvas.drawCircle(mCircle2.x - (mRadius * tmpValue), mCircle2.y, radius, mPaint);
        mPaint.setXfermode(null);
        postInvalidateDelayed(50);
    }

實現效果

在這裏插入圖片描述

關於Xfermode簡單記錄

模式
在這裏插入圖片描述
主要應用案例

  • 不規則圖片截取,圓形頭像
  • 橡皮擦,刮刮卡

源碼地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章