8

所以我需要根据屏幕的面积来改变图像的大小。图像必须是屏幕高度的一半,否则它会与一些文本重叠。

所以高度= 1/2 屏幕高度。宽度=高度*纵横比(只是试图保持纵横比相同)

我发现了一些东西:

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

但是我将如何改变java中的图像高度?如果可能的话,甚至是 XML?我似乎找不到有效的答案。

4

1 回答 1

18

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.

于 2011-01-25T20:42:45.810 回答