tomhogenkamp tomhogenkamp - 3 months ago 26
Android Question

How to change width ImageView to correct ratio?

I have this XML file with a RelativeLayout. In this RelativeLayout I have got an ImageView and a LinearLayout with a lot of Views (not displayed in the code).

<RelativeLayout
android:layout_weight="1"

android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"

android:id="@+id/imageViewDemo"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"

android:layout_alignTop="@+id/imageViewDemo"
android:layout_alignLeft="@+id/imageViewDemo"
android:layout_alignRight="@+id/imageViewDemo"
android:layout_alignBottom="@+id/imageViewDemo"
android:gravity="center"

android:orientation="vertical">

<!-- A lot of stuff -->

</LinearLayout>
</RelativeLayout>


I want the ImageView have the same width/height ratio as the ratio of the phone/tablet screen size. The height should just match the parent view, but the width must be changed to match the correct ratio. The LinearLayout must be inside the ImageView. I can simply not find a working solution. Can someone help me out? Thanks!

Answer

I want the ImageView have the same width/height ratio as the ratio of the phone/tablet screen size.

First you should get the phone/tablet screen size in order to compute the width/height ratio.

This code get the ratio:

DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
final float screenRatio = ((float)width/(float)height);

The height should just match the parent view, but the width must be changed to match the correct ratio.

For this purpose, you should change the ImageView's width in code, the height should be specified match_parent in your layout.

This code can help you change the width :

imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        int height = imageView.getHeight();
        int resultWidth = (int)(height * screenRatio);

        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        layoutParams.width = resultWidth;
        imageView.setLayoutParams(layoutParams);
    }
});

Hope this can help you.

Comments