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);
    }

}

好了,今天的分享就到这里了。

最后,我这边有个技术交流群,平常我会分享一些学习资源到群里,还可以和大家一起交流学习,需要的朋友可以扫描下面的二维码加我微信并备注「加群」,拉你进入技术交流群!

飞哥带你去装逼,一直装逼到天黑!

发布了138 篇原创文章 · 获赞 168 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/xinpengfei521/article/details/100980464