Android bitmap to drawable

Класс Drawable

Android предлагает двумерную графическую библиотеку рисования android.graphics.Drawable. Класс Drawable является базовым классом для всех классов работы с графикой. Это общая абстракция для рисуемого объекта на холсте Canvas. Класс Drawable определяет разнообразные виды графики, включая:

  • AnimationDrawable — покадровая анимация. XML-аналог
  • AnimatedRotateDrawable — анимация вращения. XML-аналог
  • AnimatedVectorDrawable — анимация векторных объектов (Android 21). XML-аналог
  • AnimatedStateListDrawable
  • BitmapDrawable — Bitmap — изображение PNG и JPG, создание, растягивание, выравнивание растра. XML-аналог
  • ClipDrawable — XML-аналог
  • ColorDrawable — заполнение цветом. XML-аналог
  • GradientDrawable — создание градиентов
  • InsetDrawable — XML-аналог

How can I convert a Bitmap image to Drawable ?

10 Answers 10

Sounds like you want to use BitmapDrawable

From the documentation:

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.

Try this it converts a Bitmap type image to Drawable

Having seen a large amount of issues with bitmaps incorrectly scaling when converted to a BitmapDrawable , the general way to convert should be:

Without the Resources reference , the bitmap may not render properly, even when scaled correctly. There are numerous questions on here which would be solved simply by using this method rather than a straight call with only the bitmap argument.

I would like to set a certain Drawable as the device’s wallpaper, but all wallpaper functions accept Bitmap s only. I cannot use WallpaperManager because I’m pre 2.1.

Also, my drawables are downloaded from the web and do not reside in R.drawable .

18 Answers 18

This piece of code helps.

Here a version where the image gets downloaded.

This converts a BitmapDrawable to a Bitmap.

A Drawable can be drawn onto a Canvas , and a Canvas can be backed by a Bitmap :

(Updated to handle a quick conversion for BitmapDrawable s and to ensure that the Bitmap created has a valid size)

METHOD 1 : Either you can directly convert to bitmap like this

METHOD 2 : You can even convert the resource into the drawable and from that you can get bitmap like this

For API > 22 getDrawable method moved to the ResourcesCompat class so for that you do something like this

So after looking (and using) of the other answers, seems they all handling ColorDrawable and PaintDrawable badly. (Especially on lollipop) seemed that Shader s were tweaked so solid blocks of colors were not handled correctly.

I am using the following code now:

Unlike the others, if you call setBounds on the Drawable before asking to turn it into a bitmap, it will draw the bitmap at the correct size!

Оцените статью
Много толка
Добавить комментарий