最近项目中遇到指纹支付的需求,有个扫指纹的动画需求
效果图
实现原理
需要重写View,在onDraw方法中完成绘制,使用canvas的drawBitmap方法:
drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint);
第一个Rect 代表要绘制的bitmap 区域,第二个 Rect 代表的是要将bitmap 绘制在屏幕的什么地方
首先,在构造函数中,初始化bitmap,paint:
mFingerGreen= ((BitmapDrawable) ContextCompat.getDrawable(mContext,R.drawable.finger_green)).getBitmap();
mFingerGrey= ((BitmapDrawable) ContextCompat.getDrawable(mContext,R.drawable.finger_grey)).getBitmap();
mLine= ((BitmapDrawable) ContextCompat.getDrawable(mContext,R.drawable.finger_line)).getBitmap();
mBitWidth=mFingerGreen.getWidth();
mBitHeight=mFingerGreen.getHeight();
mBitPaint=newPaint();
// 防抖动
mBitPaint.setDither(true);
// 开启图像过滤
mBitPaint.setFilterBitmap(true);
mSrcRect=newRect();
mDestRect=newRect();
在onDraw(Canvas canvas)方法绘制图片
@Override
protected voidonDraw(Canvas canvas) {
super.onDraw(canvas);
//显示在view中间
inthalfViewWidth =mWidth/2;
inthalfViewHeight =mHeight/2;
intleft =0;
inttop =0;
mBitPaint.setAlpha(255);
mSrcRect.set(left,top,mBitWidth,mBitHeight);
left = halfViewWidth -mFingerGrey.getWidth() /2;
top = halfViewHeight -mFingerGrey.getHeight() /2;
mDestRect.set(left,top,mBitWidth+ left,mBitHeight+ top);
canvas.drawBitmap(mFingerGrey,mSrcRect,mDestRect,mBitPaint);//画灰色底图
left =0;
top =0;
mSrcRect.set(left,top,mBitWidth,(int) (mBitHeight*mFraction));
left = halfViewWidth -mFingerGreen.getWidth() /2;
top = halfViewHeight -mFingerGreen.getHeight() /2;
mDestRect.set(left,top,mBitWidth+ left,(int) (mBitHeight*mFraction) + top);
canvas.drawBitmap(mFingerGreen,mSrcRect,mDestRect,mBitPaint);//画绿色图片
left = halfViewWidth -mLine.getWidth() /2;
canvas.drawBitmap(mLine,left,mDestRect.bottom,mBitPaint);//画线
}
最后,利用ValueAnimator,修改mFraction的值,得到每次移动的步长,invalidate()重新绘画。
public voidstartScaning() {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.f,100.f);
valueAnimator.setDuration(1000);
valueAnimator.setInterpolator(newLinearInterpolator());
valueAnimator.addUpdateListener(newValueAnimator.AnimatorUpdateListener() {
@SuppressLint("NewApi")
@Override
public voidonAnimationUpdate(ValueAnimator valueAnimator) {
mFraction= valueAnimator.getAnimatedFraction();
invalidate();
}
});
valueAnimator.addListener(newAnimator.AnimatorListener() {
@Override
public voidonAnimationStart(Animator animator) {
}
@Override
public voidonAnimationEnd(Animator animator) {
mFraction=0;
if(isAnim) {
startScaning();
}
}
@Override
public voidonAnimationCancel(Animator animator) {
}
@Override
public voidonAnimationRepeat(Animator animator) {
}
});
if(!valueAnimator.isRunning()) {
valueAnimator.start();
}
}
大功告成,最后附上需要的四张图片: