Specify the ratio of the image to be displayed on Android

2

Is there any java or attribute function in xml of the imageView to specify the ratio of the image? that is, 16:9 , 3:2 , 4:3 etc ...

<ImageView
    android:id="@+id/image_header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:background="@drawable/about_background_header"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    android:contentDescription="default desc" />

The original image is in 16:9 format but I would like it if it can be displayed in 3:2 etc ...

    
asked by Webserveis 23.08.2016 в 18:47
source

2 answers

1

I think you mean the "aspect", (Aspect Ratio). Such a property would be great because the different measures and densities that are handled in Android devices, can be displayed correctly on all devices.

There is no such property, the closest thing is to use the property adjustViewBounds :

android:adjustViewBounds = "true"

or

myImageView.setAdjustViewBounds(true);

If you want to do it programmatically it would be to calculate the measurements based on the aspect. The "aspectRatio", would be calculated for example if you define a 4: 3 aspect would be 3/4 = 0.75.

aspectRatio = 0.75;
myHeight = (int) (myWidth * aspectRatio);

This way you would get the height determined by the appearance.

    
answered by 23.08.2016 / 21:08
source
0

Thanks to @bourne's comment and @Elenasys' response, I created the following, there are pieces caught there.

Function to obtain the height taking into account the ratio with its width.

public int getHeightAspectRatio(float ratio, int width) {
        return (int) (width / ratio);
    }

And its use

imageHeader = (ImageView) findViewById(R.id.image_header);
imageHeader.setImageResource(R.drawable.about_background_header);

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

/*  16:9        3:2        4:3        1:1        3:4        2:3          */

android.view.ViewGroup.LayoutParams layoutParams = imageHeader.getLayoutParams();
layoutParams.width =  metrics.widthPixels;
layoutParams.height = getHeightAspectRatio(16f/9f, metrics.widthPixels);
imageHeader.setLayoutParams(layoutParams);
    
answered by 23.08.2016 в 23:00