![見出し画像](https://assets.st-note.com/production/uploads/images/90452658/rectangle_large_type_2_b259a58f209abf0bc3c7439bf6852abd.png?width=1200)
【Android】BitmapをDrawableに変換する2つの方法について
次のようなことを実現したかったです。
何の変哲もないBitmapがある
これをDrawableに変換したい
その変換方法には2つほど方法があります。
少なくとも自分が知ってる範囲では2つです。
AndroidにてBitmap → Drawableの変換について
これを具体的コード例も一緒にまとめてみます。
方法1.BitmapDrawableを使って変換する
どの環境でも使えそうな方法がコレ
BitmapDrawableを使ってDrawableに変換
APIレベル1から追加されたAPIです。
つまりどんな環境でも使えるということ。
▼ 一応BitmapDrawableの詳細
A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a BitmapDrawable from a file path, an input stream, through XML inflation, or from a Bitmap object.
It can be defined in an XML file with the <bitmap> element. For more information, see the guide to Drawable Resources.
▼ 上記リファレンスの意訳
Bitmapをラップ化したDrawableで、敷き詰めたり・引き伸ばしたり・配列させたりできます。BitmapDrawableはファイルパス・ストリーム・through XML inflation・Bitmapオブジェクトから生成可能。
ちなみにレイアウトXMLファイルでは<bitmap>要素によって定義することもできます。詳しくはDrawableリソースのガイドページとかを見て
こういうのが最初から用意されてました。
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ならこっちを使うのが楽なはず