0

How to manage the difference ImageView setImageResource of setImageDrawable

 2 years ago
source link: https://www.codesd.com/item/how-to-manage-the-difference-imageview-setimageresource-of-setimagedrawable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to manage the difference ImageView setImageResource of setImageDrawable

advertisements

So after tons of frustrations with trying to stretch my image properly to width I realise my real problem is that setImageResource acts different from setImageDrawable (which I'm trying to use). XML below gives me perfect width, aspect ratio stretched image with setImageResource but with setImageDrawable the image is not stretched to the width, any suggestions to how I should handle the problem? I use setImageDrawable because I get the image from the internet alternatives are welcome :)

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"/>

Oh and I've tryed scaletype, the one giving best results was centercrop but it crops which isn't desired.


This issue is really stale but in case anyone comes across it, the problem has to do with not quite a bug, but a bad implementation decision in versions of Android prior to 18. If you target 18+ you probably won't see this issue. However I'm currently targeting enterprise owned tablets at 16.

The solution is to create a superclass of ImageView that overrides onMeasure to enforce the aspect ratio:

class MyImageView extends ImageView {
    public MyImageView(Context context) {
        super(context);
    }
    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        float iwidth  = (float) View.MeasureSpec.getSize(widthMeasureSpec);
        float swidth  = (float) getDrawable().getIntrinsicWidth();
        float sheight = (float) getDrawable().getIntrinsicHeight();
        float iheight = sheight / swidth * iwidth;
        setMeasuredDimension((int)iwidth, (int)iheight);
    }
}

In your layout:

<com.mypackage.MyImageView layout_width="match_parent" etc... />

If you target Android 18+ adjustViewBounds should work as expected.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK