- VectorDrawable to Bitmap: Bitmap.setHasAlpha(boolean)’ on a null object reference
- 2 Answers 2
- converting drawable resource image into bitmap
- 6 Answers 6
- Not the answer you’re looking for? Browse other questions tagged android bitmap or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Gnzlt / ResourceUtil.java
- How to convert a Drawable to a Bitmap?
- 20 Answers 20
- 1) Drawable to Bitmap :
- 2) Bitmap to Drawable :
- VectorDrawable — часть первая
VectorDrawable to Bitmap: Bitmap.setHasAlpha(boolean)’ on a null object reference
I’m trying to get Bitmap from VectorDrawable (xml image):
But app crashes on Bitmap.createBitmap method with Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.graphics.Bitmap.setHasAlpha(boolean)’ on a null object reference error
here some simple xml drawable (comma symbol)
I tried every method from Getting Bitmap from vector drawable All of them fails on this .createBitmap method
are to big values.
I’ve added not full xml, there are more path tags, so it’s not just comma symbol with such big values:)
I tried to reduce values to 2000 (e.g.) and app stopped crashing, but it ruined my image
I made vector drawable from svg using http://inloop.github.io/svg2android/
2 Answers 2
You are trying to allocate a 16000x16000dp Bitmap that, based on the density of the display you’re running your app, must be multiplied by a factor of 2 for xhdpi, 3 for xxhdpi and 4 for xxxhdpi. This causes memory problems since you are trying to allocate a Bitmap that is larger than 1000MB.
You need to scale down your Drawable. It shouldn’t cause the quality loss you’re experiencing so I suggest you to check your SVG or the output of svg2android for errors.
Also remember that you can’t put Bitmap larger or higher than GL_MAX_TEXTURE_SIZE into ImageView. See: «Bitmap too large to be uploaded into a texture»
Источник
converting drawable resource image into bitmap
I am trying to use the Notification.Builder.setLargeIcon(bitmap) that takes a bitmap image. I have the image I want to use in my drawable folder so how do I convert that to bitmap?
6 Answers 6
You probably mean Notification.Builder.setLargeIcon(Bitmap) , right? 🙂
This is a great method of converting resource images into Android Bitmap s.
Since API 22 getResources().getDrawable() is deprecated, so we can use following solution.
Context can be your current Activity .
Here is another way to convert Drawable resource into Bitmap in android:
First Create Bitmap Image
now set bitmap in Notification Builder Icon.
In res/drawable folder,
1. Create a new Drawable Resources .
2. Input file name.
A new file will be created inside the res/drawable folder.
Replace this code inside the newly created file and replace ic_action_back with your drawable file name.
Now, you can use it with Resource ID, R.id.filename .
Not the answer you’re looking for? Browse other questions tagged android bitmap or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Gnzlt / ResourceUtil.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import android.annotation.TargetApi ; |
import android.content.Context ; |
import android.graphics.Bitmap ; |
import android.graphics.Canvas ; |
import android.graphics.drawable.BitmapDrawable ; |
import android.graphics.drawable.Drawable ; |
import android.graphics.drawable.VectorDrawable ; |
import android.os.Build ; |
import android.support.annotation.DrawableRes ; |
import android.support.graphics.drawable.VectorDrawableCompat ; |
import android.support.v4.content.ContextCompat ; |
public class ResourceUtil < |
@TargetApi ( Build . VERSION_CODES . LOLLIPOP ) |
private static Bitmap getBitmap ( VectorDrawable vectorDrawable ) < |
Bitmap bitmap = Bitmap . createBitmap(vectorDrawable . getIntrinsicWidth(), |
vectorDrawable . getIntrinsicHeight(), Bitmap . Config . ARGB_8888 ); |
Canvas canvas = new Canvas (bitmap); |
vectorDrawable . setBounds( 0 , 0 , canvas . getWidth(), canvas . getHeight()); |
vectorDrawable . draw(canvas); |
return bitmap; |
> |
private static Bitmap getBitmap ( VectorDrawableCompat vectorDrawable ) < |
Bitmap bitmap = Bitmap . createBitmap(vectorDrawable . getIntrinsicWidth(), |
vectorDrawable . getIntrinsicHeight(), Bitmap . Config . ARGB_8888 ); |
Canvas canvas = new Canvas (bitmap); |
vectorDrawable . setBounds( 0 , 0 , canvas . getWidth(), canvas . getHeight()); |
vectorDrawable . draw(canvas); |
return bitmap; |
> |
public static Bitmap getBitmap ( Context context , @DrawableRes int drawableResId ) < |
Drawable drawable = ContextCompat . getDrawable(context, drawableResId); |
if (drawable instanceof BitmapDrawable ) < |
return (( BitmapDrawable ) drawable) . getBitmap(); |
> else if (drawable instanceof VectorDrawableCompat ) < |
return getBitmap(( VectorDrawableCompat ) drawable); |
> else if (drawable instanceof VectorDrawable ) < |
return getBitmap(( VectorDrawable ) drawable); |
> else < |
throw new IllegalArgumentException ( » Unsupported drawable type » ); |
> |
> |
> |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
How to convert a Drawable to a Bitmap?
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 .
20 Answers 20
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
1) Drawable to Bitmap :
2) Bitmap to Drawable :
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!
Источник
VectorDrawable — часть первая
Предлагаю вашему вниманию перевод статьи «VectorDrawables – Part 1» с сайта blog.stylingandroid.com.
По долгу службы потребовалось мне как-то разобраться с векторной графикой. Во время поиска наткнулся я на серию статей под названием “VectorDrawable” в блоге https://blog.stylingandroid.com/. Ответов на все интересующие меня вопросы я, конечно, не нашел, но статьи очень понравились своей последовательностью и четко выверенным объемом необходимого материала. Решил поделиться переводом этих статей с обитателями хабра.
Я не переводил названия, activity, bitmap и тому подобное, потому что считаю, что так легче воспринимать информацию, ведь разработчики, в силу профессии, эти слова в русском варианте практически никогда не у потребляют. Далее следует перевод:
Одна из действительно интересных новых фишек в Lollipop – это включение VectorDrawable и связанных с ним классов, которые обеспечивают чрезвычайно мощные новые возможности для добавления сложной векторной графики (позволяет гораздо удобнее масштабировать изображения не зависимо от размеров экрана и плотности, чем растровые изображения), а также предоставляет несколько мощных инструментов для анимации оных. В этой серии статей мы рассмотрим некоторые из преимуществ, которые они нам дают. Так же рассмотрим, как можно получить действительно впечатляющие результаты из относительно небольшого количества кода.
Векторная графика – способ описания графических элементов используя геометрические фигуры. Они особенно хорошо подходят для графических элементов, созданных в приложениях, таких как Adobe Illustrator или Inkscape, где простые геометрические формы могут быть объединены в гораздо более сложные элементы. Работа с растровой графикой, с другой стороны, определяет значение цвета для каждого пикселя и особенно хорошо подходит для фото. Большим преимуществом использования векторной графики (в соответствующих случаях) является то, что изображения рендерятся в рантайме и размеры автоматически высчитываются в зависимости от плотности пикселей. Таким образом получается четкая картинка с плавными линиями, независимо от возможностей устройства. Векторные картинки, как правило, занимают значительно меньший объем памяти, чем их растровый аналог. Однако, векторные изображения требуют больше вычислительных мощностей для отрисовки, что может быть проблемой при большом количестве сложных графических элементах.
Векторная графика в андроиде была реализована с использованием нового класса – VectorDrawable, который был введен в Lollipop. Это означает, что для графических элементов, которые хорошо подходят для векторного представления мы можем заменить растровые изображения в папках mdpi, hdpi, xhdpi, xxhdpi, и xxxhdpi на один VectorDrawable в папке Drawable, который, с большой вероятностью, займет даже меньше пространства на диске, чем растровое изображение для mdpi.
Чтобы продемонстрировать это, давайте рассмотрим следующий файл svg (найти его можно по ссылке https://code.google.com/archive/p/svg-android/downloads):
Этот svg-файл занимает 2265 байт, если мы отрисуем его в bitmap с размерами 500 х 500 пикселей, и сохраним как png, тогда он займет уже 13272 байта, плюс к этому, мы должны будем использовать несколько таких картинок для разный плотностей экрана. Но SVG – это не то же самое, что VectorDrawable, поэтому мы не можем использовать его непосредственно. Тем не менее, VectorDrawable поддерживает некоторые элементы SVG. Основные компоненты, которые мы будем использовать из нашего SVG – это path. Давайте посмотрим на исходный код SVG:
Немного разберемся. Есть некоторые атрибуты родительского элемента , которые определяют размер 500х500, Есть элемент (group), который определяет границы – его мы будем игнорировать. Есть еще один элемент с Это и есть изображение логотипа, которое нам нужно. Он состоит из шести элементов , которые определяют голову, правый глаз, левый глаз, левая рука, тело и ноги, правая рука. Атрибут “fill” определяет цвет заливки (и мы можем видеть, что все они зеленые, за исключением глаз, которые залиты белым цветом), а атрибут “d” содержит маршрут линий, из которых состоит элемент. Для тех, кто хочет разобраться более детально в элементе , следует изучить SVG Path Specification, но для данной статьи это не важно, потому что мы можем просто взять их, как они есть, и использовать в наших VectorDrawables.
Итак, давайте создадим наш VectorDrawable:
Мы создали родительский элемент , который содержит информацию о размерах изображения, внутрь которого поместили элемент с шестью элементами , которые были немного модифицированы, по сравнению с svg – файлом. В данной статье поле “name” служит только для облегчения понимая того, где какой элемент. В следующих статьях они буду использоваться. Получившийся файл по-прежнему может похвастаться скромным размером в 2412 байт.
Теперь мы можем использовать этот файл как любой другой drawable:
… и если мы запустим это, то увидим красивую отрисовку:
Так что теперь мы можем существенно уменьшить размер APK, если мы используем VectorDrawable, где это уместно. Так же это позволяет упростить разработку приложения, особенно, если нужно добавлять поддержку новых плотностей экрана. Тем не менее, это не все, на что способен VectorDrawable. В следующей части статьи мы рассмотрим, как его анимировать.
Исходники к этой части статьи можно найти здесь.
Источник