解决ViewDrawableLeft左侧图片大小不可控的问题

今天在制作带文字的图片按钮的时候,使用了TextView的drawableLeft属性,但是在使用的过程中,我发现我所使用的图片资源的大小过大,导致整个效果很不和谐。可是drawableLeft并不能在xml通过属性控制它的大小,这时,我就想到了drawableLeft.setBounds()方法。

虽然我们不能在xml中获取drawableLeft对他进行控制,但是我们可以使用java代码获取它,代码只是做了一点简单的封装。

代码如下:

public class ImageTextButton extends TextView {

    private Drawable drawableLeft;
    private int scaleWidth; //dp值
    private int scaleHeight;

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

    public ImageTextButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public ImageTextButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageTextButton);

        drawableLeft = typedArray.getDrawable(R.styleable.ImageTextButton_leftDrawable);
        scaleWidth = typedArray.getDimensionPixelOffset(R.styleable
                .ImageTextButton_drawableWidth, UIUtils.dip2px(20));
        scaleHeight = typedArray.getDimensionPixelOffset(R.styleable
                .ImageTextButton_drawableHeight, UIUtils.dip2px(20));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (drawableLeft != null) {
            drawableLeft.setBounds(0, 0, UIUtils.dip2px(scaleWidth), UIUtils.dip2px(scaleHeight));
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.setCompoundDrawables(drawableLeft, null, null, null);
    }

    /**
     * 设置左侧图片并重绘
     * @param drawableLeft
     */
    public void setDrawableLeft(Drawable drawableLeft) {
        this.drawableLeft = drawableLeft;
        invalidate();
    }

    /**
     * 设置左侧图片并重绘
     * @param drawableLeftRes
     */
    public void setDrawableLeft(int drawableLeftRes) {
        this.drawableLeft = UIUtils.getContext().getResources().getDrawable(drawableLeftRes);
        invalidate();
    }
}

附上attrs:

最后在xml中调用即可,让我们看一下效果

###效果在这里

最后更新于

这有帮助吗?