简体   繁体   English

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

[英]Android Changing image size depending on Screen Size?

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. 图像必须是屏幕高度的一半,否则它会与某些文本重叠。

So Height= 1/2 Screen Height. 所以身高= 1/2屏幕高度。 Width = Height*Aspect Ratio (Just trying to keep the aspect ratio the same) 宽度=高度*宽高比(只是试图保持宽高比相同)

I found something that was: 我发现了一些东西:

Display myDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width =myDisplay.getWidth();
int height=myDisplay.getHeight();

But how would I change image height in java? 但是我如何在java中更改图像高度? or even XML if possible? 甚至是XML,如果可能的话? I can't seem to find a working answer. 我似乎找不到合适的答案。

You can do this with LayoutParams in code. 您可以在代码中使用LayoutParams执行此操作。 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: 不幸的是,没有办法通过XML指定百分比(不是直接,你可以乱用权重,但这并不总是有帮助,它不会保持你的宽高比),但这应该适合你:

//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. 不过这是我第一次尝试的。

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

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