如何在 Kotlin 中將 Bitmap 轉換為 Drawable?


本示例演示如何在 Kotlin 中將 Bitmap 轉換為 Drawable。

步驟 1 − 在 Android Studio 中建立新專案,轉到 File?New Project,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml。

示例

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/btnConvert"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="10dp"
      android:text="Convert bitmap to Drawable" />
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_below="@id/btnConvert"
      android:layout_marginTop="10dp" />
</RelativeLayout>

步驟 3 − 將以下程式碼新增到 src/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 androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var imageView: ImageView
   lateinit var button: Button
   lateinit var bitmap: Bitmap
   lateinit var drawable: Drawable
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      imageView = findViewById(R.id.imageView)
      button = findViewById(R.id.btnConvert)
      button.setOnClickListener {
         drawable = applicationContext.resources.getDrawable(R.drawable.image)
         bitmap = (drawable as BitmapDrawable).bitmap
         val d = BitmapDrawable(bitmap)
         imageView.setImageDrawable(d)
      }
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml

示例

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
   <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 執行應用程式,請開啟專案中的一個活動檔案,然後單擊工具欄中的執行圖示 。選擇你的移動裝置作為選項,然後檢視移動裝置,它將顯示你的預設螢幕

更新於: 2020-5-23

2K+ 瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.