1. 程式人生 > >Android長按Button按鈕,產生漣漪效果

Android長按Button按鈕,產生漣漪效果

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

}

其實就是在原有的canvas基礎上再畫一層,
初始化完RippleButton之後,呼叫RippleButton中的setRippleColor和setAlpha就可以設定漣漪的顏色和透明度了。

歡迎糾錯。