2013-07-21 63 views
0

我有一個大小爲1024x1024.png的位圖,我需要舒展它在不同的設備屏幕上,我嘗試使用這樣的:大位圖大小適合於小型的Android手機

// given a resource, return a bitmap with a specified maximum height 
public static Bitmap maxHeightResourceToBitmap(Context c, int res, 
     int maxHeight) { 
    Bitmap bmp = imageResourceToBitmap(c, res, maxHeight); 


    int width = bmp.getWidth(); 
    int height = bmp.getHeight(); 

    int newHeight = maxHeight; 
    int newWidth = maxHeight/2; 

    // calculate the scale - in this case = 0.4f 
    float scaleHeight = ((float) newHeight)/height; 
    float scaleWidth = ((float) newWidth)/width; 

    // createa matrix for the manipulation 
    Matrix matrix = new Matrix(); 
    // resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 

    // recreate the new Bitmap and return it 
    return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true); 
} 

// given a resource, return a bitmap with a specified maximum height 
public static Bitmap scaleWithRatio(Context c, int res, 
     int max) { 
    Bitmap bmp = imageResourceToBitmap(c, res, max); 

    int width = bmp.getWidth(); 
    int height = bmp.getHeight(); 

    // calculate the scale - in this case = 0.4f 
    float scaleHeight = ((float) max)/height; 
    float scaleWidth = ((float) max)/width; 

    // createa matrix for the manipulation 
    Matrix matrix = new Matrix(); 
    // resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 

    // recreate the new Bitmap and return it 

    return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true); 
+0

你的問題是什麼? – Simon

回答

0

爲了舒展在屏幕上的位圖我建議將位圖保留爲內存中的原始位置(不要在任何情況下使位圖本身變大)。

然後,當你看它在屏幕上,通常與ImageView,您可以設置圖像視圖ScaleTypeFIT_XY(見docs獲取更多信息)。當繪製圖像填充整個ImageView時,這將在屏幕上展開圖像。還要確保ImageView通過相應地設置其LayoutParameters填充整個屏幕(例如填充父項)。

調整內存中位圖大小的唯一真正原因是爲了節省內存,使它們的尺寸更小更小。這一點很重要,因爲Android設備的堆棧有限,如果您的位圖內存太大,它們將填滿整個堆,並且會遇到OutOfMemory錯誤。如果您遇到內存問題,請參閱此tutorial