Resizing ImageView to fit to aspect ratio(调整 ImageView 的大小以适应纵横比)
问题描述
我需要调整 ImageView 的大小,使其适合屏幕,保持相同的纵横比.以下条件成立:
I need to resize an ImageView such that it fits to the screen, maintains the same aspect ratio. The following conditions hold:
- 图像是固定宽度(屏幕宽度的大小)
- 图片是从网上下载的,即大小只能稍后确定
- 每张图片的宽高比会有所不同;有的高,有的方,有的平
- ImageView 的 height 需要根据纵横比改变,变大或变小
- 裁剪多余的高度,不能像默认那样有很多空白空间.
- Images are a fixed width (size of the width of screen)
- Images are downloaded from the Internet, i.e. size can only be determined later
- Aspect ratio for each image will vary; some are tall, some are square, some are flat
- ImageView's height needs to change, either bigger or smaller based on the aspect ratio of the
- Excess height is cropped, can't have a lot of empty space like it is by default.
例如,在 400 像素宽的屏幕上显示一个 50x50 的微小图像会将图像缩放到 400x400 像素.一张 800x200 的图片会缩放到 400x100.
For example, a tiny 50x50 image on a 400 px width screen would scale the image up to 400x400 px. A 800x200 image would scale to 400x100.
我查看了大多数其他线程,许多建议的解决方案,例如简单地更改 adjustViewBounds
和 scaleType
只会缩小图像,而不会将其放大.
I've looked at most of the other threads, and many proposed solutions like simply changing adjustViewBounds
and scaleType
will only scale down an image, and not scale it up.
推荐答案
ImageView mImageView; // This is the ImageView to change
// Use this in onWindowFocusChanged so that the ImageView is fully loaded, or the dimensions will end up 0.
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
// Abstracting out the process where you get the image from the internet
Bitmap loadedImage = getImageFromInternet (url);
// Gets the width you want it to be
intendedWidth = mImageView.getWidth();
// Gets the downloaded image dimensions
int originalWidth = loadedImage.getWidth();
int originalHeight = loadedImage.getHeight();
// Calculates the new dimensions
float scale = (float) intendedWidth / originalWidth;
int newHeight = (int) Math.round(originalHeight * scale);
// Resizes mImageView. Change "FrameLayout" to whatever layout mImageView is located in.
mImageView.setLayoutParams(new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT));
mImageView.getLayoutParams().width = intendedWidth;
mImageView.getLayoutParams().height = newHeight;
}
这篇关于调整 ImageView 的大小以适应纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调整 ImageView 的大小以适应纵横比
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01