ScratchView。这是一个Android刮奖效果控件。
实现效果:
示例代码:
绘制出刮层效果
package com.clock.scratch; import ...; /** * Created by Clock on 2016/8/26. */ public class ScratchView extends View { ... public ScratchView(Context context) { super(context); TypedArray typedArray = context.obtainStyledAttributes(R.styleable.ScratchView); init(typedArray); } ... private void init(TypedArray typedArray) { ... mMaskColor = typedArray.getColor(R.styleable.ScratchView_maskColor, DEFAULT_MASKER_COLOR); mMaskPaint = new Paint(); mMaskPaint.setAntiAlias(true);//抗锯齿 mMaskPaint.setDither(true);//防抖 setMaskColor(mMaskColor); ... } /** * 设置蒙板颜色 * * @param color 十六进制颜色值,如:0xffff0000(不透明的红色) */ public void setMaskColor(int color) { mMaskPaint.setColor(color); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(mMaskBitmap, 0, 0, mBitmapPaint);//绘制图层遮罩 } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); createMasker(w, h); } /** * 创建蒙层 * * @param width * @param height */ private void createMasker(int width, int height) { mMaskBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mMaskCanvas = new Canvas(mMaskBitmap); Rect rect = new Rect(0, 0, width, height); mMaskCanvas.drawRect(rect, mMaskPaint);//绘制生成和控件大小一致的遮罩 Bitmap } } <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="ScratchView"> <!--蒙层的颜色--> <attr name="maskColor" format="color|reference" /> </declare-styleable> </resources>