본문 바로가기
Android

[Android] 안드로이드 ConstraintLayout에서 1:1 비율로 뷰 설정하기

by quessr 2024. 6. 10.

 

ConstraintLayout에서 layout_constraintDimensionRatio 사용법

 

ConstraintLayout 매우 유연하고 강력한 레이아웃 시스템으로, layout_constraintDimensionRatio 속성 사용하여 너비와 높이의 비율을 쉽게 설정할 있습니다.

예를 들어, 너비와 높이를 1:1 비율로 설정하고 싶은 경우 다음과 같이 코드를 작성할 있습니다.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="1:1"/>
        
</androidx.constraintlayout.widget.ConstraintLayout>

 

여기서 android:layout_width와 android:layout_height를 둘 다 0dp로 설정하고, app:layout_constraintDimensionRatio 속성을 1:1로 설정합니다.

이 속성은 너비와 높이의 비율을 지정하는 것으로, 1:1은 너비와 높이가 동일하게 설정된다는 의미입니다.

참고로, layout_constraintDimensionRatio 속성은 constraint 제약 조건이 설정된 상태에서만 동작합니다.

예제에서는 Start, End, Top 제약 조건이 설정되어 있습니다.