欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android长按Button按钮,产生涟漪效果

程序员文章站 2022-06-09 16:58:27
...

package com.zhang.ripple;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class RippleButton extends Button {

private float cx;
private float cy;
private float radius;
private Paint rPaint;
// true为开始绘制
private boolean star = false;
// 设置色值
private int mRippleColoe;
// 设置透明度
private float mAlpha = 255;


public RippleButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub

    rPaint = new Paint();
    // 防锯齿
    rPaint.setAntiAlias(true);
    // 防抖动
    rPaint.setDither(true);
    rPaint.setColor(Color.GREEN);
    // 设置透明度0~255
    rPaint.setAlpha(50);
}

/**
 * 设置涟漪颜色
 * @param mRippleColoe
 */
public void setRippleColor(int mRippleColoe){
    this.mRippleColoe = mRippleColoe;
    onColorOrAlphaChange();
}

/**
 * 设置透明度
 * @see android.view.View#setAlpha(float)
 */
public void setAlpha(float mAlpha){
    this.mAlpha = mAlpha;
    onColorOrAlphaChange();
}

private void onColorOrAlphaChange() {
    rPaint.setColor(mRippleColoe);

    if (mAlpha != 255) {
        int tAlpha = rPaint.getAlpha();
        int realAlpha = (int) (tAlpha*(mAlpha/255f));
        rPaint.setAlpha(realAlpha);
    }
}

Handler hand = new Handler(){
    public void handleMessage(android.os.Message msg) {
        invalidate();
    };
}; 

@Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        cx = event.getX();
        cy = event.getY();
        radius = 100;

        star = true;
        new Thread(){

            public void run() {
                while (star) {
                    try {
                        radius = radius + 10;
                        hand.sendEmptyMessage(1);
                        sleep(16);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            };
        }.start();

        break;
    case MotionEvent.ACTION_UP:
        // 停止绘制涟漪
        star = false;
        radius = 0;
        invalidate();

        break;
    case MotionEvent.ACTION_MOVE:
        break;

    default:
        break;
    }

    return super.onTouchEvent(event);
}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub

    canvas.drawCircle(cx, cy, radius, rPaint);

    super.onDraw(canvas);
}

}

下载:http://download.csdn.net/download/u014333053/9878584

其实就是在原有的canvas基础上再画一层,
初始化完RippleButton之后,调用RippleButton中的setRippleColor和setAlpha就可以设置涟漪的颜色和透明度了。

欢迎纠错。