Home » Android » imageview – Android Changing image size depending on Screen Size?

imageview – Android Changing image size depending on Screen Size?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.
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? or even XML if possible? I can’t seem to find a working answer.

How to&Answers:

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.