2012-08-28 102 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