Android 自定義一個簡單的刮獎 View

實現思路:

使用相對佈局,先寫一個 TextView,然後自定義一個 EraseView,寫一個同樣大小的 EraseView 覆蓋在 TextView 上面即可。

先看下效果圖:

在這裏插入圖片描述

代碼也比較簡單,我就直接貼上了:

public class EraseView extends View {

    private boolean isMove = false;
    private Bitmap bitmap = null;
    private Bitmap frontBitmap = null;
    private Path path;
    private Canvas mCanvas;
    private Paint paint;

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

    public EraseView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EraseView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mCanvas == null) {
            createEraseBitmap();
        }
        canvas.drawBitmap(bitmap, 0, 0, null);
        mCanvas.drawPath(path, paint);
    }

    public void createEraseBitmap() {
        bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_4444);
        frontBitmap = createBitmap(Color.GRAY, getWidth(), getHeight());

        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(60);

        path = new Path();

        mCanvas = new Canvas(bitmap);
        mCanvas.drawBitmap(frontBitmap, 0, 0, null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float ax = event.getX();
        float ay = event.getY();

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            isMove = false;
            path.reset();
            path.moveTo(ax, ay);
            invalidate();
            return true;
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            isMove = true;
            path.lineTo(ax, ay);
            invalidate();
            return true;
        }
        return super.onTouchEvent(event);
    }

    public Bitmap createBitmap(int color, int width, int height) {
        int[] rgb = new int[width * height];

        for (int i = 0; i < rgb.length; i++) {
            rgb[i] = color;
        }

        return Bitmap.createBitmap(rgb, width, height, Config.ARGB_8888);
    }

}

好了,今天的分享就到這裏了。

最後,我這邊有個技術交流羣,平常我會分享一些學習資源到羣裏,還可以和大家一起交流學習,需要的朋友可以掃描下面的二維碼加我微信並備註「加羣」,拉你進入技術交流羣!

飛哥帶你去裝逼,一直裝逼到天黑!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章