Android水波纹效果按钮

2020-07-03 11:05:56 浏览数 (1)

RippleButton.gif

基本思路是自定义控件继承至Button,记录手势抬起坐标,利用RadialGradient实现效果
代码语言:javascript复制
    private Paint ripplePaint = new Paint();
    private RadialGradient radialGradient;
    //递增的半径
    private float radius = -1;
    private float currentX;
    private float currentY;
在onTouchEvent事件中记录手指抬起的坐标
代码语言:javascript复制
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                //记录手抬起的点
                currentX = event.getX();
                currentY = event.getY();
                radius = 1;
                //通知重绘
                postInvalidate();
                break;
        }
        return super.onTouchEvent(event);
    }
onDraw方法中实现效果
代码语言:javascript复制
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (radius > 0 && radius < getMeasuredWidth()) {
            radialGradient = new RadialGradient(currentX, currentY, radius, Color.TRANSPARENT, Color.GREEN, Shader.TileMode.CLAMP);
            ripplePaint.setShader(radialGradient);

            canvas.drawCircle(currentX, currentY, radius, ripplePaint);

            postInvalidateDelayed(10);

            radius  = 10;
        } else {
            radius = -1;
        }
    }
项目地址:https://gitee.com/aruba/ShaderApplication.git

0 人点赞