How to set maxHeight over DimensionRatio with ConstraintLayout?

后端 未结 3 929
粉色の甜心
粉色の甜心 2021-01-05 14:41

I\'m trying to display an image centered in parent with a dimension ratio of 1220:1000 AND a maximum height of 300dp (to keep the image small even with large screen)

相关标签:
3条回答
  • 2021-01-05 15:07

    If you want to enforce max_height and keep the dimension ratio at the same time, you need to constrain the width based on height. You can achieve that by adding W to your ratio:

    app:layout_constraintDimensionRatio="W,1220:1000"

    This will constrain the height first and then set the width accordingly to satisfy the ratio.

    More info on how this dimension ratio works can be found in the documentation.

    0 讨论(0)
  • 2021-01-05 15:14

    Have you tried to add the tag maxHeight?

    android:maxHeight="200dp"
    
    0 讨论(0)
  • 2021-01-05 15:16

    If you want to maximize the area with a dimension ratio and a max height, but you don't know if width or height is going to be adjusted, better don't to use layout_constraintDimensionRatio + layout_constraintHeight_max. They don't work well together.

    Here I put my solution in the case you have an image 16:9 which will use full width while max height is not yet reached, otherwise it will respect max height, and width will be adjusted:

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
            <!-- This space view makes ImageView expands to its corresponding height -->
            <Space
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/imageview" />
    
            <com.a3.sgt.ui.widget.AspectRatioImageView
                android:id="@+id/imageview"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:adjustViewBounds="true"
                app:dominantMeasurement="height"
                app:aspectRatioEnabled="true"
                app:aspectRatio="1.778"
                android:scaleType="centerCrop"
                app:layout_constraintHeight_max="400dp"
                tools:src="@drawable/placeholder_glacier"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    I used a custom ImageView I had in my gist which adjusts to aspect ratio, in order to avoid using layout_constraintDimensionRatio which causes the problem together with layout_constraintHeight_max

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