Android에서 ImageView 이미지 크기 조절 시 종횡비 유지하기
이 튜토리얼에서는 Android의 ImageView에 표시되는 이미지를 확대·축소할 때 원본 이미지의 종횡비(aspect ratio)를 그대로 유지하는 방법을 단계별로 살펴봅니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 정보를 모두 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 XML 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/my_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:scaleType="fitXY"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>주요 속성을 간단히 정리하면 다음과 같습니다.
- adjustViewBounds="true" — ImageView의 경계가 이미지의 종횡비를 유지하도록 자동으로 조정됩니다. 너비 또는 높이 중 하나라도 wrap_content로 설정했을 때 가장 잘 동작합니다.
- scaleType — 종횡비를 지키려면
fitCenter,fitStart,fitEnd,centerInside같은 값을 사용하는 것이 좋습니다. 반면fitXY는 ImageView 영역에 맞춰 이미지를 강제로 늘리기 때문에 종횡비가 왜곡될 수 있습니다.
3단계: MainActivity 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView my_image = (ImageView) findViewById(R.id.my_image);
my_image.setBackgroundResource(R.drawable.flower);
}
}위 코드는 res/drawable 폴더에 있는 flower 이미지를 ImageView의 배경으로 지정합니다. 참고로 종횡비 유지가 중요하다면 setBackgroundResource() 대신 setImageResource()를 사용하는 것이 바람직합니다. 배경(background)으로 설정된 이미지는 scaleType의 영향을 받지 않고 ImageView 영역 전체에 늘어나기 때문입니다.
4단계: 매니페스트 확인
Manifests/AndroidManifest.xml에 아래 코드가 올바르게 들어 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run 아이콘을 클릭하세요. 기기 선택 목록에서 본인의 모바일 기기를 고르면, 해당 기기 화면에 아래와 같은 실행 결과가 표시됩니다.
