Setting a background image to a view stretches my view

前端 未结 7 2078
梦如初夏
梦如初夏 2020-12-05 17:54

I created a background image bitmap for a view and now the view is being stretched to the size of the background image....

is this normal?



        
7条回答
  •  春和景丽
    2020-12-05 18:02

    The reason is quite simple. You gotta see the View::getSuggestedMinimumWidth/Height method.

    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }
    
    protected int getSuggestedMinimumHeight() {
        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
    }
    

    Seeing that, you may know why the background makes a view bigger, especially why assign a BitmapDrawable to it.

    and the simple solution is to wrap that Drawable (eg. BitmapDrawable), then returns 0 for getMinimumHeight() and getMinimumWidth(), and better to override getIntrinsicHeight() and getIntrinsicWidth() to returns -1.

    support-v7 has a DrawableWrapper which delegates calls to another drawable when necessary. you can extends that one and override methods talked above.

    and if you don't use support-v7 (WoW! you are awesome), copy that class to your project is also fine.

    https://android.googlesource.com/platform/frameworks/support/+/1949ae9aeaadf52ad7bd7bb74ca5419c67ea7f65/v7/appcompat/src/android/support/v7/internal/widget/DrawableWrapper.java

提交回复
热议问题