Android的改变图像大小取决于屏幕尺寸? [英] Android Changing image size depending on Screen Size?

查看:167
本文介绍了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屏幕高度。 宽=高*宽比(只是想保持纵横比相同)

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.

推荐答案

您可以在code这样与的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的改变图像大小取决于屏幕尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆