Android Changing image size depending on Screen Size?

前端 未结 1 997
旧时难觅i
旧时难觅i 2020-12-10 06:09

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.<

相关标签:
1条回答
  • 2020-12-10 07:01

    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.

    0 讨论(0)
提交回复
热议问题