【Android】BitmapをDrawableに変換する2つの方法について
次のようなことを実現したかったです。
何の変哲もないBitmapがある
これをDrawableに変換したい
その変換方法には2つほど方法があります。
少なくとも自分が知ってる範囲では2つです。
AndroidにてBitmap → Drawableの変換について
これを具体的コード例も一緒にまとめてみます。
方法1.BitmapDrawableを使って変換する
どの環境でも使えそうな方法がコレ
BitmapDrawableを使ってDrawableに変換
APIレベル1から追加されたAPIです。
つまりどんな環境でも使えるということ。
▼ 一応BitmapDrawableの詳細
▼ 上記リファレンスの意訳
こういうのが最初から用意されてました。
BitmapをBitmapDrawbleに変換するコード例
こういうコードで変換できました。
▼ 実際に試したコード例
/// Drawableを表示したいImageView
val imageView:ImageView = findViewById(R.id.image_view)
/// 変換したいBitmapオブジェクト
val bitmap = BitmapFactory.decodeFile(
"/path/to/image/hogehoge.png"
)
/// BitmapDrawableに変換する
val drawable = BitmapDrawable(resources, bitmap)
/// ImageViewにDrawableをセット
imageView.setImageDrawable(drawable)
こういう感じでBitmap→Drawableに変換できます。
どんな環境でも使える汎用的な方法だと思う
方法2.Bitmap.toDrawable() で変換が便利!
これはKotlin限定の方法です。
それはBitmap.toDrawable()による変換
コードも短くて済むし分かりやすい最高です。
▼ 実際にはこのようなコードを書けばOK
/// Drawableを表示したいImageView
val imageView:ImageView = findViewById(R.id.image_view)
/// 変換したいBitmapオブジェクト
val bitmap = BitmapFactory.decodeFile(
"/path/to/image/hogehoge.png"
)
/// BitmapDrawableに変換する
val drawable = bitmap.toDrawable(resources)
/// ImageViewにDrawableをセット
imageView.setImageDrawable(drawable)
とても分かりやすいです。
ただし1点注意なのは bitmap.toDrawable(resources) のようにアプリResourcesを渡す必要があることです。アプリ内リソースにはアクセスしないですが、必須なので一応渡しておきます。
Kotlinならこっちを使うのが楽なはず
この記事が気に入ったらサポートをしてみませんか?