1

我有一个 8 mp 的图像,但它无法在 ImageView 上显示,因为它的文件太大。如何使用 BitmapFactory 重新调整它的大小,然后将此新图像作为 XML 中 ImageView 的源传递?

我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select" />

    <Button
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Info" />

</LinearLayout>

<ImageView
    android:id="@+id/test_image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />


</LinearLayout>

我的活动:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ImageView view;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize=8; //also tried 32, 64, 16
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, options);
    Drawable d = new BitmapDrawable(bmp);

    view = (ImageView) findViewById(R.id.test_image_view);
    view.setImageDrawable(d);

    setContentView(R.layout.main);


}
4

2 回答 2

4

You can't pass it into XML

For what? Load it, when you need it. In your case it's better to use BitmapFactory.Options:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=16; //image will be 16x smaller than an original. Note, that it's better for perfomanse to use powers of 2 (2,4,8,16,32..).
Bitmap bmp=BitmapFactory.decodeSomething(..., options) //use any decode method instead of this
Drawable d=new BitmapDrawable(bmp);

and then just set it to your ImageView

ImageView iv; //initialize it first, of course. For example, using findViewById.
iv.setImageDrawable(d);

Note, that you should recycle your bitmap, after you used it (after ImageView is not visible anymore):

bmp.recycle();
于 2012-06-07T20:17:10.877 回答
2

我不相信您可以以编程方式调整图像大小,然后在 XML 中使用它。XML 文件中的所有内容几乎都是静态的,并且在编译时读取,因此没有回头路。您将使用 BitmapFactory,然后在 java 中设置图像。

于 2012-06-07T20:08:50.183 回答