get drawable exactly the size of the imageView to

2019-06-14 11:58发布

问题:

I am using Universal Image View to load images into my application.

This is the method I implemented

public static void setBitmapToAImageviewUIL(final ImageView imageView, String uriPath, String imageName)
{
  if(imageName != null && !imageName.equals(""))
  {
     //We use the local image as a temporary placeholder
     DisplayImageOptions options = new DisplayImageOptions.Builder()
           .showStubImage(Utilities.getDrawableResource(imageName))
           .cacheOnDisc()
           .cacheInMemory()
           .imageScaleType(ImageScaleType.EXACTLY)
           .bitmapConfig(Bitmap.Config.ARGB_8888)
           .build();

     imageLoader.displayImage(uriPath, imageView, options);
  }

}

The logic is this: I have some of the images in the drawables. First I use the local drawable as a placeholder (showStubImage). Utilities.getDrawableResource() retruns the drawable. Then the image downloaded from the server will be displayed when it finishes downloading.

My problem

The temporary image used as the placeholder is larger than the image downloaded from the server. So at first the image is big, then when the new image finishes downloading it scales down. How can I make them both exactly the same size of the imageView?

I am trying to avoid manual resize code to make them the same size. Thanks

PS: The Utilities.getDrawableResource() uses getResource().getIdentifier() to get the correct drawable.

回答1:

There're a few different approaches depending on what you want to achieve, and how much information you have up-front.

One way is set your imageview to an exact size on your XML (e.g. width:match_parent height:144dp) and let both the server and your drawable scale inside that.

If you have access to the image-server size before downloading it, you can set the imageView layoutparams to those exact values and let the drawable resize to that (and the server will just fit perfectly)

I'm thinking you could use XML shape drawables and/or 9patch to make it scale nicer, but you would still need one of the two methods above.