部分代碼
@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簡單記錄
模式
主要應用案例
- 不規則圖片截取,圓形頭像
- 橡皮擦,刮刮卡