Android Changing image size depending on Screen Size?

23,410

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.

Share:
23,410
QQWW1
Author by

QQWW1

Updated on July 18, 2022

Comments

  • QQWW1
    QQWW1 almost 2 years

    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.

  • QQWW1
    QQWW1 over 13 years
    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 still
  • Kevin Coppock
    Kevin Coppock over 13 years
    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.
  • QQWW1
    QQWW1 over 13 years
    Ahhh... I see what I did wrong, I substituted "R.id.rootlayout" for my ImageView, not my RelativeLayout.. Thanks!!!!
  • Geert Weening
    Geert Weening over 11 years
    small typo, int orgHeight = image.getDrawable().getIntrinsicHeight(); instead of width
  • Kevin Coppock
    Kevin Coppock over 11 years
    @GeertWeening Thanks, fixed. :)