安卓 (Android) 一張圖片實現按下效果的Button

在Android開發過程中,一定會用到帶圖片的按鈕,傳統方法是UI出兩張圖,一張正常狀態,一張按下狀態。其實多數時候,按鈕按下的效果就是正常狀態的圖片改變一下亮度,廢話少說,直接上代碼。

<code>import android.content.Context;import android.graphics.Bitmap;import android.graphics.Bitmap.Config;import android.graphics.Canvas;import android.graphics.ColorMatrix;import android.graphics.ColorMatrixColorFilter;import android.graphics.Paint;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.graphics.drawable.StateListDrawable;import android.util.AttributeSet;import android.widget.Button;/** * 單張圖片實現按下效果的Button * * @author CharlesRich * @email [email protected] * @mobile 18602438878 * @create 2020-02-10 18:55 */public class ImageButton extends Button {    private Context context;    public ImageButton(Context context) {        super(context);        this.context = context;        init();    }    public ImageButton(Context context, AttributeSet attrs) {        super(context, attrs);        this.context = context;        init();    }    public ImageButton(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        this.context = context;        init();    }    private void init() {        setBackgroundDrawable(newSelector());    }    /**     * 傳入改變亮度前的bitmap,返回改變亮度後的bitmap     *     * @param bitmap     * @return     */    private Drawable changeBrightnessBitmap(Bitmap bitmap) {        Bitmap bmp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),                Config.ARGB_8888);        int brightness = 60 - 127;        ColorMatrix cMatrix = new ColorMatrix();        cMatrix.set(new float[]{1, 0, 0, 0, brightness, 0, 1,                0, 0, brightness,/** 改變亮度 */                0, 0, 1, 0, brightness, 0, 0, 0, 1, 0});        Paint paint = new Paint();        paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));        Canvas canvas = new Canvas(bmp);        /** 在Canvas上繪製一個Bitmap */        canvas.drawBitmap(bitmap, 0, 0, paint);        return new BitmapDrawable(bmp);    }    /**     * 設置Selector     */    private StateListDrawable newSelector() {        StateListDrawable bg = new StateListDrawable();        Drawable normal = getBackground();        Drawable pressed = changeBrightnessBitmap(((BitmapDrawable) getBackground()).getBitmap());        /** View.PRESSED_ENABLED_STATE_SET */        bg.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);        /** View.ENABLED_STATE_SET */        bg.addState(new int[]{android.R.attr.state_enabled}, normal);        /** View.EMPTY_STATE_SET */        bg.addState(new int[]{}, normal);        return bg;    }}/<code>


分享到:


相關文章: