안드로이드 ImageView에 테두리 추가하기
이 튜토리얼에서는 안드로이드 앱에서 ImageView에 테두리(border)를 설정하는 방법을 단계별로 살펴봅니다. XML 셰이프(shape) 드로어블을 활용하면 별도의 이미지 파일 없이도 원하는 두께와 색상의 테두리를 손쉽게 만들 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — activity_main.xml 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 핵심은 ImageView의 android:background 속성에 테두리용 드로어블을 지정하고, android:padding 값으로 이미지와 테두리 사이의 여백을 조절하는 것입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@layout/image_border"
android:padding="7dp"
android:scaleType="centerInside"
android:src="@drawable/image" />
</RelativeLayout>
3단계 — MainActivity.java 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다. 별도의 로직 없이 레이아웃만 연결하면 됩니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
참고: 최신 버전의 Android Studio에서는 android.support.v7.app.AppCompatActivity 대신 androidx.appcompat.app.AppCompatActivity를 사용해야 합니다.
4단계 — 테두리 드로어블 생성
res/layout 폴더에 image_border.xml 파일을 새로 만들고 아래 코드를 추가합니다. <stroke> 요소의 width(두께)와 color(색상) 값을 변경하면 테두리 스타일을 자유롭게 조정할 수 있습니다.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<stroke
android:width="8dp"
android:color="#01fee9" />
</shape>
팁: 셰이프 드로어블은 일반적으로 res/drawable 폴더에 저장하는 것이 표준적인 방식입니다. 이 경우에는 background 속성을 @drawable/image_border로 참조하면 됩니다.
5단계 — AndroidManifest.xml 설정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run 아이콘을 클릭하세요. 목록에서 실행할 모바일 기기를 선택하면, 기기 화면에 테두리가 적용된 ImageView가 표시됩니다.
