欢迎大家来到IT世界,在知识的湖畔探索吧!
在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;
}
}
欢迎大家来到IT世界,在知识的湖畔探索吧!
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/17786.html