2012-08-28 101 views
2

我正在嘗試編寫簡單的幻燈片放映程序。我希望它顯示不同大小的圖片,然後縮放,因此寬度會填滿屏幕。我可以改變圖像視圖的大小,並在調試器中設置爲新的寬度,但它不會縮放位圖, 是這樣做的一種方式嗎?Android:嘗試縮放ImageView,因此圖像填充寬度並縮放到高度

代碼:

ImageView picImage = (ImageView) findViewById(0);// R.id.viewpic); 
try { 
    String FileName = "canon20.png"; 
    AssetManager assetManager = getAssets(); 
    InputStream inputStream; 
    inputStream = assetManager.open(FileName); 
    Bitmap icon = BitmapFactory.decodeStream(inputStream); 

    int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); 
    int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); 
    int bw = icon.getWidth(); 
    float t = (float) screenWidth/(float) bw; 

    picImage.setImageBitmap(icon); 
    picImage.getLayoutParams().width = screenWidth; 
    picImage.getLayoutParams().height = (int) (icon.getHeight() * t); 
} catch (IOException e) { 
} 
+0

請訪問http://計算器.com/questions/6410364 /如何縮放位圖到屏幕大小來縮放位圖。 – DigitalGhost

+0

它看起來像picImage的佈局參數的問題。你能顯示XML代碼嗎?如果您只涉及填充可用空間,請考慮使用FILL_XY設置圖像視圖的'setScaleType'(http://developer.android.com/reference/android/widget/ImageView.html#setScaleType(android.widget.ImageView.ScaleType)或MATRIX(用於更多的控制)在這種情況下,你並不需要處理RAW圖像屬性 – xandy

回答

2

是的,有一個非常簡單的方法來做到這一點:

只需使用下面的代碼來重新調整你的位圖:

ImageView picImage = (ImageView) findViewById(0);// R.id.viewpic); 
try { 
String FileName = "canon20.png"; 
AssetManager assetManager = getAssets(); 
InputStream inputStream; 
inputStream = assetManager.open(FileName); 
Bitmap icon = BitmapFactory.decodeStream(inputStream); 

int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); 
int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); 
int bw = icon.getWidth(); 
float t = (float) screenWidth/(float) bw; 

picImage.setImageBitmap(icon); 
picImage.getLayoutParams().width = screenWidth; 
picImage.getLayoutParams().height = (int) (icon.getHeight() * t); 
// The following line is the one that scales your bitmap. 
Bitmap scaledIcon = Bitmap.createScaledBitmap(icon, screenWidth, (int) icon.getHeight() * t, false); 
} catch (IOException e) { 
} 
+0

謝謝你的幫助,我只需要添加一行代碼:) –

+0

對我來說,它應該是這個其他問題的正確答案:http://stackoverflow.com/questions/5554682/android-imageview-adjusting-parents-height-and-fitting-width http://stackoverflow.com/questions/2991110/android-how -to-拉伸的圖像到所述屏幕寬度,同時維持縱橫RA – marceloquinta