Why are the Width / Height of the drawable in ImageView wrong?

ε祈祈猫儿з 提交于 2020-01-29 11:34:05

问题


Should be a simple one.

When I pull image.getDrawable().getIntrinsicWidth() I get a value larger than the source image width. It's X coordinate is returning 2880 instead of 1920 which is 1.5 times too big?

I wondered wether the ImageView having a scaleType of "center" effected it but, according to the documentation:

"Center the image in the view, but perform no scaling."

Here is the source:

<ImageView  
    android:id="@+id/backgroundImage"   
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:src="@drawable/background"
    android:scaleType="center"/>

回答1:


You said the drawable is from your /res folder. Which folder is it in?

  • /res/drawable
  • /res/drawable-mdpi
  • /res/drawable-hdpi

    etc..

And what is the density of the device you are testing on? Is it a Nexus S with general density of 240dpi? Because if your source drawable is located in the drawable-mdpi folder and you are testing on a 240dpi device, then the Android system will automatically scale the drawable up by a factor of 1.5 so that the physical size will be consistent with the baseline device density at 160dpi.

When you call getIntrinsicWidth() what is returned is the size the drawable wants to be after Android scales the drawable. You'll notice that 2880 = 1920 * 1.5

If you placed the drawable in /res/drawable the Android system treats those drawables as meant for mdpi devices, thus the upscaling in your Nexus S. If this was meant for hdpi screens and you do not want this to upscale then try placing it in drawable-hdpi




回答2:


Have you tried to multiply height and width by density:

getResources().getDisplayMetrics().density

Is your drawable in ressources or download from the web? If it is downloaded, you have to give it the density:

DisplayMetrics metrics = new DisplayMetrics();
getContext().getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources r = new Resources(getContext().getAssets(), metrics, null);
BitmapDrawable bmd = new BitmapDrawable(r, bitmap);



回答3:


Check if it is returning the value of it's displayed size, which is not it's actual size. For example, a 50x320px banner ad on a traditional 800x480 phone displays as 75x480.

Should be able to compare against density (or your eyes!) to see what it is doing.




回答4:


This is probably going to be nothing to with the issue you're having, but just for kicks I'll suggest it to be sure anyway: Are you specifying android:minSdkVersion in your manifest?

Only reason I mention this is because for a while I wasn't doing so in a project, and I learned that this screws the screen density up and caused all sorts of strange problems.



来源:https://stackoverflow.com/questions/6536418/why-are-the-width-height-of-the-drawable-in-imageview-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!