简体   繁体   English

如何获得ImageView来填充屏幕的整个宽度?

[英]How do you get an ImageView to fill the entire width of the screen?

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. 这似乎正在完成我的计算,总是返回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()); 浮动高度= 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. 由于某些原因,如果位图的宽度大于屏幕宽度,则它将始终返回0,因为Float不允许任何小数位。

An example would be: 一个例子是:

Screen Size: 800px; 屏幕尺寸:800px; Image Width: 500px; 图片宽度:500像素; Image Height: 400px; 图片高度:400px;

The new image should then have a width of 800px and height of 640px. 然后,新图像的宽度应为800px,高度应为640px。 Because the float isn't working correctly instead of having 400 x 1.6 (ie800/500), the code is dropping the decimal and doing 400 x 1. 由于浮点数无法正常运行,而不是具有400 x 1.6(即800/500),因此代码将小数点掉了,然后执行400 x 1。

Any clues? 有什么线索吗?

将整数除法的结果强制转换为float:

float height = bitmap.getHeight() * ((float)width / bitmap.getWidth());

Don't scale the bitmap yourself, let the ImageView do it. 不要自己缩放位图,而是让ImageView进行缩放。

See ImageView.setScaleType() . 请参见ImageView.setScaleType() Use ScaleType.CENTER_CROP or CENTER_INSIDE, depending on what you need. 根据需要使用ScaleType.CENTER_CROP或CENTER_INSIDE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM