代码如下。
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/img"
android:layout_width="36dip"
android:layout_height="36dip"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
MainActivity.java
package com.czq.testdrawable;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
Drawable drawable = img.getDrawable();
Log.i("MainActivity", "Bounds.getIntrinsicHeight = " + drawable.getIntrinsicHeight());
Log.i("MainActivity", "Bounds.getIntrinsicWidth = " + drawable.getIntrinsicWidth());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
运行在分辨率为 h的机器上。
Bounds.getIntrinsicHeight =72
Bounds. getIntrinsicWidth=72
运行在分辨率为 m的机器上。
01-19 12:06:40.772: INFO/MainActivity(358):Bounds.getIntrinsicHeight = 48
01-19 12:06:40.772: INFO/MainActivity(358):Bounds.getIntrinsicWidth = 48
48=72/1.5
运行在分辨率为 l的机器上。
01-19 12:11:23.442: INFO/MainActivity(325):Bounds.getIntrinsicHeight = 36
01-19 12:11:23.442: INFO/MainActivity(325):Bounds.getIntrinsicWidth = 36
36=72/2
运行在分辨率为 xh的机器上。
01-19 12:15:59.937: DEBUG/SntpClient(70):Bounds.getIntrinsicHeight = 96
01-19 12:15:59.937: DEBUG/SntpClient(70):Bounds.getIntrinsicWidth = 96
总结:当图片只有一份,只放在一个文件夹中,例如放在drawwable-hdpi中。当程序运行在其他分辨率的机器上时,图片会按比例拉伸或者压缩来适应当前机器。
把高清图,放在了-m下,然后又运行在高清的机器上。
结果是:
例如一张480x800的图片。会变成480*1.5 x 800 *1.5
所以高清图一定要放在-h 或者-xh文件夹下,否者会因为图片拉伸的过大,程序内存占用的较多。
建议9path 的图,直接放在drawable目录下,不需要按照分辨率去拉伸或者压缩。