Android 根据屏幕尺寸更改图像尺寸?

Android Changing image size depending on Screen Size?(Android 根据屏幕尺寸更改图像尺寸?)

本文介绍了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 根据屏幕尺寸更改图像尺寸?

基础教程推荐