我正在尝试从网络上获取图像并将其填充整个屏幕宽度。这似乎正在做我的计算,它总是返回 0。
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Integer width = metrics.widthPixels;
try {
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif").getContent());
float height =bitmap.getHeight() * (width/bitmap.getWidth());
bitmap = Bitmap.createScaledBitmap(bitmap, width, (int) height, true);
imageView.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
如果由于以下行,此代码将使程序崩溃:
float 高度 =bitmap.getHeight() * (宽度/bitmap.getWidth());
出于某种原因,如果位图的宽度大于屏幕宽度,它将始终返回 0,因为 Float 不允许使用任何小数位。
一个例子是:
屏幕尺寸:800px;图片宽度:500px;图片高度:400px;
新图像的宽度应为 800 像素,高度为 640 像素。由于 float 无法正常工作,而不是 400 x 1.6(即 800/500),因此代码会舍去小数并执行 400 x 1。
有什么线索吗?
最佳答案
将整数除法的结果转换为 float :
float height = bitmap.getHeight() * ((float)width / bitmap.getWidth());
关于java - 如何让 ImageView 填满屏幕的整个宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9157265/