安卓 (Android) 一张图片实现按下效果的Button
在Android开发过程中,一定会用到带图片的按钮,传统方法是UI出两张图,一张正常状态,一张按下状态。其实多数时候,按钮按下的效果就是正常状态的图片改变一下亮度,废话少说,直接上代码。
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 18602438878@qq.com
* @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;
}
}
在使用这个方式实现按钮按下效果时,需要注意,按钮图片不能太大,否则可能造成oom 异常。