效果如下:
呱呱卡開(kāi)獎(jiǎng)前
呱呱卡開(kāi)獎(jiǎng)后
實(shí)現(xiàn)思路
網(wǎng)上有使用Xfermode來(lái)實(shí)現(xiàn)刮刮卡,這里提供另一種思路簡(jiǎn)潔的實(shí)現(xiàn)
一張呱呱卡有三層,最底層我用一個(gè)TextView控件顯示中獎(jiǎng)內(nèi)容,中間層是刮完之后的顯示圖樣,最上面一層是刮刮卡的封面。手指刮除封面的過(guò)程就是把刮刮卡最上面一層裁剪的過(guò)程。
涉及的知識(shí)點(diǎn)
- canvas.clipPath(),Path類,Region.Op類
- onDraw方法和onTouchEvent方法的配合
核心代碼如下:
public class LotteryView extends View {
public static final int STROKE_WIDTH = 15;
private float mEventX;
private float mEventY;
/**
* 呱呱卡封面 畫筆
*/
private Paint mOverlayPaint;
private RectF mRectBorder;
/**
* 呱呱卡邊緣 畫筆
*/
private Paint mStrokePaint;
private RectF mRectFill;
private Path mClipPath;
public LotteryView(Context context) {
this(context,null,0);
}
public LotteryView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LotteryView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
Bitmap lotteryOverlay = BitmapFactory.decodeResource(getResources(), R.drawable.icon_lottery_overlay);
mOverlayPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mOverlayPaint.setShader(new BitmapShader(lotteryOverlay, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
mStrokePaint = new Paint();
mStrokePaint.setAntiAlias(true);
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setColor(Color.BLACK);
mStrokePaint.setStrokeWidth(STROKE_WIDTH);
mClipPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
if (mRectBorder == null) {
mRectBorder = new RectF(0, 0, getWidth(), getHeight());
}
if (mRectFill == null) {
mRectFill = new RectF(0, 0, getWidth(), getHeight());
}
canvas.drawRoundRect(mRectBorder, 10, 10, mStrokePaint);
if (mEventX != 0 || mEventY != 0) {
mClipPath.addCircle(mEventX, mEventY, 50, Path.Direction.CW);
canvas.clipPath(mClipPath, Region.Op.DIFFERENCE);
}
canvas.drawRect(mRectFill, mOverlayPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_MOVE:
mEventX = event.getX();
mEventY = event.getY();
invalidate();
break;
}
return true;
}
}
布局里的使用
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="120dp"
>
<TextView
android:id="@+id/tv_lottery_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="20sp"
android:background="@android:color/darker_gray"
android:text="恭喜您,榮獲2016年年度最佳程序員"
/>
<com.sugary.roundimageview.LotteryView
android:layout_width="match_parent"
android:layout_height="120dp"
/>
</RelativeLayout>
小結(jié)
- 刮刮卡的中獎(jiǎng)內(nèi)容是放在TextView控件,作為最底層顯示。
- 如果項(xiàng)目里需要有刮卡完成后回調(diào),可以計(jì)算刮除的面積與刮刮卡總面積的比例,超過(guò)一定值,即認(rèn)為呱卡完成。
- 后續(xù)的優(yōu)化方向可以是,把底層的TextView放到LotteryView自定義控件里