이 튜토리얼에서는 안드로이드 앱에서 Bitmap을 Drawable로 변환하는 방법을 단계별로 살펴봅니다. 이미지를 화면에 표시하거나 배경으로 설정할 때 두 타입 간의 변환이 자주 필요하기 때문에, 안드로이드 개발자라면 꼭 알아두어야 할 기본 기능입니다.
핵심 원리: BitmapDrawable 클래스
Bitmap을 Drawable로 변환하려면 android.graphics.drawable.BitmapDrawable 클래스를 사용합니다. 이 클래스는 Bitmap 객체를 감싸서 Drawable 형태로 다룰 수 있게 해주며, 생성자에 Bitmap 객체를 전달하기만 하면 손쉽게 변환할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼 하나와 결과를 표시할 ImageView로 구성된 간단한 레이아웃입니다.
<?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"> <Button android:id="@+id/btnConvert" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Convert bitmap to Drawable" /> <ImageView android:id="@+id/imageView" android:layout_below="@id/btnConvert" android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
3단계 — MainActivity 구현
src/MainActivity.java 파일에 아래 코드를 추가합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
Bitmap bitmap;
Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
button = findViewById(R.id.btnConvert);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 리소스에서 Drawable 가져오기
drawable = getApplicationContext().getResources().getDrawable(R.drawable.image);
// Drawable에서 Bitmap 추출
bitmap = ((BitmapDrawable) drawable).getBitmap();
// Bitmap을 다시 Drawable로 변환
Drawable d = new BitmapDrawable(bitmap);
// ImageView에 적용
imageView.setImageDrawable(d);
}
});
}
}코드 동작 흐름
버튼을 클릭하면 다음 순서로 처리가 진행됩니다.
1. 리소스(R.drawable.image)에서 Drawable 객체를 가져옵니다.
2. 해당 Drawable을 BitmapDrawable로 캐스팅하여 내부의 Bitmap을 추출합니다.
3. 추출한 Bitmap으로 새로운 BitmapDrawable 객체를 생성합니다.
4. setImageDrawable() 메서드를 통해 ImageView에 변환된 Drawable을 표시합니다.
참고: 최신 API에서의 권장 방식
getResources().getDrawable()은 API 22부터 deprecated(사용 중단 권고)되었습니다. 최신 프로젝트에서는 아래와 같이 ContextCompat을 사용하는 것이 좋습니다.
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.image);
4단계 — 매니페스트 설정
AndroidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <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 아이콘을 클릭하세요. 실행할 기기 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱이 실행됩니다.
앱이 실행되면 Convert bitmap to Drawable 버튼을 눌러보세요. 지정한 이미지가 Bitmap에서 Drawable로 변환되어 ImageView에 정상적으로 표시되는 것을 확인할 수 있습니다.
