[Android]一個高自由度的刮刮卡刮獎效果Demo

本Demo旨在實現刮刮卡效果,優點是可自由實現刮層下的內容,附贈一個可隨路徑移動的橡皮擦。

在寫正文之前,先感謝一下鴻洋大神的【Android 自定義控件實現刮刮卡效果 真的就只是刮刮卡么】這篇文章,此文章手把手教你實現一個刮刮卡效果,有助于從0開始理解刮獎效果是怎么實現的(絕大多數的刮獎效果實現原理是一樣的)。

效果圖

trimmedVideo_eo_20190726_175154.gif

實現

刮獎效果實現的核心是PorterDuffXfermode這個類,PorterDuffXfermode是一種集合概念,交集、并集等圖像的混合顯示模式。它提供了16個常用Mode,而我這里將要使用的Mode是PorterDuff.Mode.CLEAR,clear的意思很直白,清除。此外還有一個Mode, PorterDuff.Mode.DST_OUT可以使用,此處這兩個Mode實現的效果是一樣的。PorterDuffXfermode所有Mode的使用效果請自行百度。

刮獎效果實現原理

將Bitmap設置成底層畫板,創建畫筆,設置畫筆Xfermode為PorterDuff.Mode.CLEAR,然后重寫onTouchEvent,使用畫筆畫出手勢移動的路徑,那么畫筆所經過的地方就會被擦除。

GuaGuaKaLayer.java


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
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.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.adminstrator.guaguakaapplication.R;

/**
 * Created by Administrator on 2019/7/26.
 * 刮刮卡的蒙層View
 */

public class GuaGuaKaLayer extends View {
    /**
     * 繪制線條的Paint,即用戶手指繪制Path
     */
    private Paint mOutterPaint = new Paint();

    /**
     * 記錄用戶繪制的Path
     */
    private Path mPath = new Path();

    /**
     * 內存中創建的Canvas
     */
    private Canvas mCanvas;

    /**
     * mCanvas繪制內容在其上
     */
    private Bitmap mBitmap;

    /**
     * 蒙層和橡皮擦
     * */
    private Bitmap mBackBitmap;
    private Bitmap moveBitmap;

    /**
     * 記錄手勢移動位置
     * */
    private int mLastX;
    private int mLastY;

    /**
     * 用于判斷何時算刮開完成
     * */
    private boolean isComplete = false;

    /**
     * 用于判斷是否顯示橡皮擦
     * */
    private boolean isDownOrMove = false;

    private Resources resources;

    public GuaGuaKaLayer(Context context) {
        this(context, null);
    }

    public GuaGuaKaLayer(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GuaGuaKaLayer(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        resources = context.getResources();
        init();
    }


    private void init() {
        mPath = new Path();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        //初始化bitmap
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        //設置畫筆
        mOutterPaint.setColor(Color.RED);
        mOutterPaint.setAntiAlias(true);
        mOutterPaint.setDither(true);
        mOutterPaint.setStyle(Paint.Style.STROKE);
        mOutterPaint.setStrokeJoin(Paint.Join.ROUND);
        mOutterPaint.setStrokeCap(Paint.Cap.ROUND);
        //設置畫筆寬度
        mOutterPaint.setStrokeWidth(20);

        //將Bitmap精確縮放到指定的大小
        Bitmap tempBackBitmap = Bitmap.createBitmap(BitmapFactory.decodeResource(resources, R.drawable.guaguaceng));
        Bitmap tempMoveBitmap = Bitmap.createBitmap(BitmapFactory.decodeResource(resources, R.drawable.cleaner));
        moveBitmap = Bitmap.createScaledBitmap(tempMoveBitmap,100,100,true);
        mBackBitmap= Bitmap.createScaledBitmap(tempBackBitmap, width, height, true);

        mCanvas.drawBitmap(mBackBitmap, 0, 0, null);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!isComplete) {
            drawPath();
            canvas.drawBitmap(mBitmap, 0, 0, null);
            if(isDownOrMove){
                 //繪制橡皮擦
                canvas.drawBitmap(moveBitmap, mLastX - moveBitmap.getWidth()/2, mLastY - moveBitmap.getHeight()/2, null);
            }
        }
    }

    /**
     * 繪制線條
     * */
    private void drawPath() {
        mOutterPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
//        mOutterPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
        mCanvas.drawPath(mPath, mOutterPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastX = x;
                mLastY = y;
                mPath.moveTo(mLastX, mLastY);

                isDownOrMove = true;
                break;

            case MotionEvent.ACTION_MOVE:
                int dx = Math.abs(x - mLastX);
                int dy = Math.abs(y - mLastY);
                if (dx > 3 || dy > 3) {
                    mPath.lineTo(x, y);
                }
                mLastX = x;
                mLastY = y;

                isDownOrMove = true;
                break;
            case MotionEvent.ACTION_UP:
                isDownOrMove = false;
                new Thread(mRunnable).start();
                break;
        }
        invalidate();
        return true;
    }


    /**
     * 統計擦除區域任務
     */
    private Runnable mRunnable = new Runnable() {
        private int[] mPixels;

        @Override
        public void run() {

            int w = getWidth();
            int h = getHeight();

            float wipeArea = 0;
            float totalArea = w * h;

            Bitmap bitmap = mBitmap;

            mPixels = new int[w * h];

            /**
             * 拿到所有的像素信息
             */
            bitmap.getPixels(mPixels, 0, w, 0, 0, w, h);

            /**
             * 遍歷統計擦除的區域
             */
            for (int i = 0; i < w; i++) {
                for (int j = 0; j < h; j++) {
                    int index = i + j * w;
                    //被擦除
                    if (mPixels[index] == 0) {
                        wipeArea++;
                    }
                }
            }

            /**
             * 根據所占百分比,進行一些操作
             */
            if (wipeArea > 0 && totalArea > 0) {
                int percent = (int) (wipeArea * 100 / totalArea);

                if (percent > 70) {
                    isComplete = true;
                    postInvalidate();
                }
            }
        }

    };
}

使用

在布局文件中使用FrameLayout包裹刮刮樂底層內容和蒙層
文件中TextView可替換成任意控件和布局,自由實現刮層下的內容

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.adminstrator.guaguakaapplication.MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/p1" />

        <com.adminstrator.guaguakaapplication.widget.GuaGuaKaLayer
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </FrameLayout>
    
</LinearLayout>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容