Android刮刮乐效果
刮刮乐中奖效果,纯属好玩,效果不错。
一、思路:
自定义组件ScratchCardView
二、效果图:
三、关键代码:
public class ScratchCardView extends View {
//处理文字
private String mText = "欧王中奖了";
private Paint mTextPaint;
private Rect mRect;
//处理图层
private Paint mForePaint;
private Path mPath;
private Bitmap mBitmap;//加载资源文件
private Canvas mForeCanvas;//前景图Canvas
private Bitmap mForeBitmap;//前景图Bitmap
//记录位置
private int mLastX;
private int mLastY;
private volatile boolean isClear;//标志是否被清除
public ScratchCardView(Context context) {
this(context, null);
}
public ScratchCardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ScratchCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mRect = new Rect();
mPath = new Path();
//文字画笔
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(Color.GREEN);
mTextPaint.setStyle(Paint.Style.FILL);
mTextPaint.setTextSize(30);
mTextPaint.getTextBounds(mText, 0, mText.length(), mRect);
//擦除画笔
mForePaint = new Paint();
mForePaint.setAntiAlias(true);
mForePaint.setAlpha(0);
mForePaint.setStrokeCap(Paint.Cap.ROUND);
mForePaint.setStrokeJoin(Paint.Join.ROUND);
mForePaint.setStyle(Paint.Style.STROKE);
mForePaint.setStrokeWidth(30);
mForePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
//通过资源文件创建Bitmap对象
mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg1);
mForeBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
//双缓冲,装载画布
mForeCanvas = new Canvas(mForeBitmap);
mForeCanvas.drawBitmap(mBitmap, 0, 0, null);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText(mText, mForeBitmap.getWidth() / 2 - mRect.width() / 2, mForeBitmap.getHeight() / 2 + mRect.height() / 2, mTextPaint);
if (!isClear) {
canvas.drawBitmap(mForeBitmap, 0, 0, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = (int) event.getX();
mLastY = (int) event.getY();
mPath.moveTo(mLastX, mLastY);
break;
case MotionEvent.ACTION_MOVE:
mLastX = (int) event.getX();
mLastY = (int) event.getY();
mPath.lineTo(mLastX, mLastY);
break;
case MotionEvent.ACTION_UP:
new Thread(mRunnable).start();
break;
default:
break;
}
mForeCanvas.drawPath(mPath, mForePaint);
invalidate();
return true;
}
四、项目demo源码结构图:
有问题或者需要完整源码demo的可以看简介联系我,也可以私信我,我每天都看私信的