android 带图标Button

宁欣怿
2023-12-01

实现思路:继承AppCompatButton,重写onDraw(Canvas canvas)

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.support.v7.widget.AppCompatButton;



public class ImageTextButton extends AppCompatButton {
    private int resourceId = 0;
    private Bitmap bitmap;

    public ImageTextButton(Context context) {
        super(context, null);
    }

    public ImageTextButton(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.setClickable(true);
        resourceId = R.drawable.success1;
        bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
    }

    public void setIcon(int resourceId) {
        this.bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        //图片居中偏左显示
        int x = (this.getMeasuredWidth() - bitmap.getWidth()) / 2-(int)(this.getTextSize()*2);
        int y = (this.getMeasuredHeight()-bitmap.getHeight())/2;
//        int x = this.getMeasuredWidth()/2;
//        int y = this.getMeasuredHeight()/2;
        canvas.drawBitmap(bitmap, x, y, null);
//        canvas.translate(0, (this.getMeasuredHeight() / 2) - (int) this.getTextSize()/2);
        super.onDraw(canvas);

    }
}

 

 类似资料: