Android Studio ImageView Change Only Width and Maintain Aspect Ratio

Issue

I’ve got an imageview, like this:

    <ImageView
        android:id"@+id/add_image_signup"
        android:layout_width"wrap_content"
        android:layout_height"wrap_content"
        android:layout_below"@id/other_text"
        android:layout_centerHorizontal"true"
        android:layout_marginTop"20dp"
        app:srcCompat"@drawable/add_button" />

which I’m trying to scale programmatically (based on device size) with Layout Params. Something like this works great:

        val displayMetrics  DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val height  displayMetrics.heightPixels
        val width  displayMetrics.widthPixels

        val addImage  findViewById<ImageView>(R.id.add_image_signup)
        val layoutParams  addImage.getLayoutParams()
        layoutParams.width  width * 0.3
        layoutParams.height  height * 0.1

        addImage.setLayoutParams(layoutParams)

and scales the image. However, I’d like to scale only the width, and have the height scale accordingly so that the image maintains its aspect ratio.

I tried only scaling the width, like this:

        val addImage  findViewById<ImageView>(R.id.add_image_signup)
        val layoutParams  addImage.getLayoutParams()
        layoutParams.width  width * 0.3
        addImage.setLayoutParams(layoutParams)

but that seems to have no effect.

Is there a way to only specify the width value, and have the height scale accordingly so that the image maintains its aspect ratio?

Thanks

Solution

Take the set width and divide it by the aspect ratio to get the height then set it like the code below

Display display  requireActivity().getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics  new DisplayMetrics();
        display.getMetrics(outMetrics);

        Resources r  getResources();

        float density  getResources().getDisplayMetrics().density;
        //float dpHeight  outMetrics.heightPixels / density;
        float dpWidth  outMetrics.widthPixels / density;

        int widthPX  Math.round(TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, yourImageFixedWidthValue, r.getDisplayMetrics()));

        float imageAspectRatio  (float) 335 / 217;
        float imageWidth  widthPX;
        float imageHeight  imageWidth / imageAspectRatio;

        imageView.getLayoutParams().height  Math.round(TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, imageHeight, r.getDisplayMetrics()));
        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);

Answered By – kelvinoff

Leave a Comment