[Android/Kotlin] 이미지 크기를 가로세로의 비율로 지정하는 방법

코코아의 개발일지·2024년 6월 5일
0

Android-Kotlin

목록 보기
29/31
post-thumbnail

✍🏻 요구사항 분석

  1. 화면의 비율에 맞춰서 위젯을 배치하려면(ex. 이미지가 가로의 80%를 차지)
  2. 레이아웃에 넣어야하는 이미지의 가로, 세로의 비율이 정해져 있다면
    위 상황에 써먹을 수 있는 방법이다.

화면 사이즈에 맞춘 이미지를 보여주어야 하는 상황에서는 width와 height의 사이즈를 직접 지정하는 하드코딩 방법은 사용하면 안 된다.
이럴 때는 기준이 되는 가로 or 세로의 크기를 지정하고, 나머지의 길이는 비율로 설정해서 보여주면 된다.

💻 코드 작성

<ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scaleType="fitCenter"
        android:layout_marginHorizontal="15dp"
        app:layout_constraintDimensionRatio="375:600"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

width를 match_parent로 두고, height는 width에 맞게 비율로 설정한 모습이다.

피그마를 보면, 화면 위에 표시하는 이미지가 width는 화면의 가로에 꼭 맞고, width와 height의 비율이 375*675로 나와있는 것을 확인할 수 있다.
이를 위해 코드에서는 height는 0dp로 하고,
layout_constraintDimensionRatio="375:600"
로 비율을 설정해 준다.
부모 레이아웃이 ConstraintLayout일 때 사용할 수 있는 방법이다.


만약, 부모가 ConstraintLayout이 아니라면
android:adjustViewBounds="true" 속성을 활용할 수 있다.

<ImageView
                android:id="@+id/group_list_empty_iv"
                android:layout_width="263dp"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_group_empty"
                android:adjustViewBounds="true"/>

위처럼 width에만 크기를 지정해 주면 adjustViewBounds를 통해 height는 넣어준 이미지 사이즈대로 자동으로 지정이 된다.

📚 참고 자료

profile
우당탕탕 성장하는 개발자

0개의 댓글