will come true

[Android] ImageView 뷰 영역을 이미지 크기에 딱 맞추기 본문

Android

[Android] ImageView 뷰 영역을 이미지 크기에 딱 맞추기

haehyun 2022. 1. 12. 22:23

문제 상황

ImageView 뷰를 사용할 때 layout_width, layout_height의 속성값을 wrap_content로 지정하면 뷰의 크기가 src속성에 지정한 이미지에 안맞게 지나치게 크게 잡히게 된다.

<레이아웃 파일>
AppBarLayout 안에 ToolBar와 ImageView를 순서대로 배치함.

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/lake"/>


</com.google.android.material.appbar.AppBarLayout>

 

<원한 결과 / 실제 결과>

 

실제 레이아웃 화면을 보면 아래와 같이 ImageView 뷰 영역이 이미지 크기보다 크게 잡혀있어서 다른 뷰를 아래에 추가로 배치할 수가 없다.

 

해결

android:adjustViewBounds 속성true로 설정하면 이미지의 가로세로 길이에 비례해 뷰의 크기가 맞춰진다.
여기서 추가로 maxWidth, maxHeight 속성을 이용하면 뷰를 출력할 최대 크기를 지정해줄 수 있다.

 

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/lake"/>

</com.google.android.material.appbar.AppBarLayout>

 

Comments