Android Changing image size depending on Screen Size?(Android 根据屏幕尺寸更改图像尺寸?)
问题描述
所以我需要根据屏幕区域更改图像的大小.图片必须是屏幕高度的一半,否则它会与一些文本重叠.
So I need to change the size of an image depending on the area of the screen. The image will have to be half of the screen height, because otherwise it overlaps some text.
所以高度= 1/2 屏幕高度.Width = Height*Aspect Ratio(只是尽量保持纵横比不变)
So Height= 1/2 Screen Height. Width = Height*Aspect Ratio (Just trying to keep the aspect ratio the same)
我发现了一些东西:
Display myDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width =myDisplay.getWidth();
int height=myDisplay.getHeight();
但是如何在 java 中更改图像高度?如果可能的话,甚至是 XML?我似乎找不到有效的答案.
But how would I change image height in java? or even XML if possible? I can't seem to find a working answer.
推荐答案
您可以在代码中使用 LayoutParams
来做到这一点.不幸的是,没有办法通过 XML 指定百分比(不是直接指定,你可以乱用权重,但这并不总是有帮助,而且它不会保持你的纵横比),但这应该适合你:
You can do this with LayoutParams
in code. Unfortunately there's no way to specify percentages through XML (not directly, you can mess around with weights, but that's not always going to help, and it won't keep your aspect ratio), but this should work for you:
//assuming your layout is in a LinearLayout as its root
LinearLayout layout = (LinearLayout)findViewById(R.id.rootlayout);
ImageView image = new ImageView(this);
image.setImageResource(R.drawable.image);
int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
int orgWidth = image.getDrawable().getIntrinsicWidth();
int orgHeight = image.getDrawable().getIntrinsicHeight();
//double check my math, this should be right, though
int newWidth = Math.floor((orgWidth * newHeight) / orgHeight);
//Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
newWidth, newHeight);
image.setLayoutParams(params);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
layout.addView(image);
可能过于复杂,也许有更简单的方法?不过,这是我首先尝试的.
Might be overcomplicated, maybe there's an easier way? This is what I'd first try, though.
这篇关于Android 根据屏幕尺寸更改图像尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android 根据屏幕尺寸更改图像尺寸?
基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01