Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드에서 Drawable을 Bitmap으로 변환하는 방법

이 예제는 Kotlin을 사용해 안드로이드에서 Drawable을 Bitmap으로 변환하는 방법을 단계별로 설명합니다.

프로젝트 설정

1단계 − Android Studio에서 새 프로젝트를 생성합니다. 메뉴에서 File → New Project로 이동한 후, 필요한 항목을 모두 입력하여 새 프로젝트를 만듭니다.

2단계 − res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

레이아웃 예제

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="4dp"
    tools:context=".MainActivity">
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/btnConvert"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Convert Drawable to Bitmap" />
</LinearLayout>

위 레이아웃은 이미지를 표시할 ImageView와 변환 작업을 실행할 Button 하나로 구성되어 있으며, 요소들이 화면 중앙에 세로로 정렬됩니다.

메인 액티비티 구현

3단계 − src/MainActivity.kt 파일에 다음 코드를 추가합니다.

import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val imageView: ImageView = findViewById(R.id.imageView)
        val btnConvert: Button = findViewById(R.id.btnConvert)
        btnConvert.setOnClickListener {
            val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
            imageView.setImageBitmap(bitmap)
            Toast.makeText(applicationContext, "Image converted to Bitmap",
            Toast.LENGTH_SHORT).show()
        }
    }
}

여기서 핵심은 BitmapFactory.decodeResource() 메서드입니다. 이 메서드는 리소스에 포함된 Drawable 이미지를 디코딩하여 Bitmap 객체로 만들어 주며, 변환된 Bitmap은 setImageBitmap()을 통해 ImageView에 바로 적용할 수 있습니다.

매니페스트 파일 설정

4단계 − androidManifest.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <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 아이콘Kotlin으로 안드로이드에서 Drawable을 Bitmap으로 변환하는 방법을 클릭합니다. 옵션 목록에서 사용 중인 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 나타납니다.

버튼을 누르면 Drawable 이미지가 Bitmap으로 변환되어 ImageView에 표시되고, 하단에는 변환이 완료되었다는 토스트 메시지가 짧게 나타납니다.

Kotlin으로 안드로이드에서 Drawable을 Bitmap으로 변환하는 방법

참고: 벡터 Drawable을 변환하는 방법

BitmapFactory.decodeResource()는 PNG, JPG 같은 비트맵 리소스에 적합합니다. 반면 VectorDrawable처럼 캔버스에 직접 그려야 하는 Drawable은 아래와 같은 유틸리티 함수를 사용하는 것이 좋습니다.

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable

fun drawableToBitmap(drawable: Drawable): Bitmap {
    // 이미 BitmapDrawable이라면 내부 비트맵을 그대로 반환
    if (drawable is BitmapDrawable) {
        return drawable.bitmap
    }
    val width = if (drawable.intrinsicWidth > 0) drawable.intrinsicWidth else 1
    val height = if (drawable.intrinsicHeight > 0) drawable.intrinsicHeight else 1
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    drawable.setBounds(0, 0, canvas.width, canvas.height)
    drawable.draw(canvas)
    return bitmap
}

이 함수는 Drawable이 이미 BitmapDrawable인 경우 불필요한 복사 없이 기존 비트맵을 재사용하고, 그렇지 않으면 새로운 Bitmap을 생성한 뒤 캔버스에 Drawable을 그려서 반환합니다. 상황에 맞는 방식을 선택하면 더 안정적으로 이미지를 처리할 수 있습니다.