Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Chuyển đổi Drawable sang Bitmap trong Android Kotlin

Giới thiệu

Ví dụ này minh họa cách chuyển đổi một Drawable (tài nguyên vẽ) thành Bitmap để thao tác pixel, lưu file hoặc hiển thị lên ImageView trong Android Kotlin.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền thông tin.

Bước 2: Giao diện (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"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_launcher_background" />

    <Button
        android:id="@+id/btnConvert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Convert Drawable to Bitmap" />

</LinearLayout>

Bước 3: MainActivity.kt

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.drawable.toBitmap

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val imageView = findViewById<ImageView>(R.id.imageView)
        val btnConvert = findViewById<Button>(R.id.btnConvert)

        btnConvert.setOnClickListener {
            // Cách 1: Dùng extension function toBitmap() (API 22+ từ androidx.core)
            val drawable: Drawable = resources.getDrawable(R.drawable.ic_launcher_background, theme)
            val bitmap: Bitmap = drawable.toBitmap()

            // Cách 2: Nếu Drawable đã là BitmapDrawable
            // val bitmap = (drawable as BitmapDrawable).bitmap

            imageView.setImageBitmap(bitmap)
            Toast.makeText(this, "Converted to Bitmap: ${bitmap.width}x${bitmap.height}", Toast.LENGTH_SHORT).show()
        }
    }
}

Bước 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút "Convert" → ImageView hiển thị Bitmap chuyển đổi từ Drawable resource.

Các trường hợp thường gặp:

  • VectorDrawable → Bitmap: cần render vào Canvas vì không phải BitmapDrawable.
  • Drawable có bounds chưa set → gọi drawable.setBounds(0, 0, width, height) trước khi draw.
  • Dùng Bitmap.createBitmap() + Canvas cho VectorDrawable.