代码和刮刮乐图片参考网络
实现效果
MainActivity
import android.app.Activity;
import android.os.Bundle;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}
}
ScratchCardView
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;public class ScratchCardView extends View {//类成员变量private Paint mPaint;//画笔private Path mPath;//手指滑动的路径private Canvas mCanvas;//临时画布private Bitmap mBackGroundBitmap;//未刮奖前背景private Bitmap mForeGroundBitmap;//前景图(灰色)private int mLastX, mLastY;//滑动结束点的坐标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() {mPaint = new Paint();//初始化画笔mPaint.setAlpha(0);//设置alpha不透明度,范围为0~255mPaint.setAntiAlias(true);//消除锯齿边,给画笔设置平滑的属性mPaint.setStyle(Paint.Style.STROKE);//描边效果mPaint.setStrokeCap(Paint.Cap.ROUND);//圆角效果mPaint.setStrokeJoin