2012-06-07 35 views
1

我有一個8 mp的圖像,但它不能顯示在ImageView上,因爲它太大的文件。如何用一個BitmapFactory重新調整大小,然後將這個新圖像作爲ImageView的源代碼傳遞給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

你不能把它傳遞到XML

爲了什麼?在需要時加載它。 在你的情況下,最好使用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); 

,然後只需將其設置爲您ImageView

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

注意,你應該回收您的位圖,你使用後(ImageView的後不再可見):

bmp.recycle(); 
+0

它仍然崩潰,我張貼我的代碼,你可以快速瀏覽它嗎? – Aneem

+0

@Aneem當然,它張貼到你的問題 –

+0

@Aneem首先是 - 你不'decodeResource'方法設置好的你的選擇(這應該是最後的參數)。其次 - 也許值'16'是不是你正在尋找(你也可以嘗試32,64等) –

2

我不相信,你可以通過編程方式調整圖像大小,然後在XML中使用它。 XML文件中的所有內容幾乎都是靜態的,並且在編譯時讀取,因此不會再回到它。 您將使用BitmapFactory,然後在java中設置圖像。

+0

啊我想你是對 – Aneem

+0

那麼請選擇它作爲一個答案:) –

+0

PS。我經常用字符串來解決這個問題,這是我得出的結論。 –

相關問題