如何让 ImageView 填满屏幕的整个宽度?
我正在尝试从网络上获取图像并将其填充整个屏幕宽度。这似乎正在做我的计算,它总是返回 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 height =bitmap.getHeight() * (width/bitmap.getWidth());
由于某种原因,如果位图的宽度大于屏幕宽度,它将始终返回 0,因为 Float 不允许有任何小数位。
一个例子是:
屏幕尺寸:800px;图片宽度:500px;图片高度:400px;
新图像的宽度应为 800 像素,高度为 640 像素。因为浮点数无法正常工作,而不是 400 x 1.6(即 800/500),所以代码会删除小数并执行 400 x 1。
有任何线索吗?
I'm trying to take an image from the web and have it fill the entire width of the screen. This seems to be working up to doing my calculations which are always returning 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();
}
This code will crash the program if because of the line:
float height =bitmap.getHeight() * (width/bitmap.getWidth());
For some reason if the bitmap's width is greater than the screen width it will always return 0 because the Float isn't allowing for any decimal places.
An example would be:
Screen Size: 800px; Image Width: 500px; Image Height: 400px;
The new image should then have a width of 800px and height of 640px. Because the float isn't working correctly instead of having 400 x 1.6 (i.e.800/500), the code is dropping the decimal and doing 400 x 1.
Any clues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将整数除法的结果转换为浮点数:
Cast the result of integer devision to float:
不要自己缩放位图,让 ImageView 来完成。
请参阅 ImageView.setScaleType()< /a>.使用 ScaleType.CENTER_CROP 或 CENTER_INSIDE,具体取决于您的需要。
Don't scale the bitmap yourself, let the ImageView do it.
See ImageView.setScaleType(). Use ScaleType.CENTER_CROP or CENTER_INSIDE, depending on what you need.