Android Changing image size depending on Screen Size?
Asked Answered
D

1

8

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.

Dannydannye answered 25/1, 2011 at 20:16 Comment(0)
H
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.

Horne answered 25/1, 2011 at 20:42 Comment(4)
It seems I'm getting a Force Close if I try to run this. If this helps at all, under LogCat, I'm getting "Uncaught handler: thread main exiting due to uncaught exception". I'm not exactly sure what this means though. Ps.I'm kinda new to android stillDannydannye
Well, this is kind of a generalized example, your situation is going to vary of course (variable names, XML ids, etc.). Under LogCat, it should have a trace of what exception occured, and in what line of the file.Horne
Ahhh... I see what I did wrong, I substituted "R.id.rootlayout" for my ImageView, not my RelativeLayout.. Thanks!!!!Dannydannye
small typo, int orgHeight = image.getDrawable().getIntrinsicHeight(); instead of widthCaddell

© 2022 - 2024 — McMap. All rights reserved.