Question

According to documentation here, A png resource should be converted to a BitmapDrawable. However I'm observing a strange behavior wherein a png file which has only black pixels in it is resulting in a crash because of ClassCastException (wrapped in InvocationTargetException) if I try to do the following in a Custom View's constructor :

  ...
  tempDrawable = typedArr.getDrawable(R.styleable.CustomView_src); // Source points to a png file
  Log.i("TestPNGToResource", "Canonical Class Name " + tempDrawable.getClass().getCanonicalName());
  tempBitmap = ((BitmapDrawable) tempDrawable).getBitmap();
  ...

I see the following logged on android 2.2 and 2.3

09-24 13:21:37.575: I/TestPNGToResource(532): Canonical Class Name android.graphics.drawable.ColorDrawable

Why is the resource not being converted to a BitmapDrawable?

Was it helpful?

Solution

This is an optimization performed by aapt. It is able to recognize images made of a single color and turn them into, well, a single color instead of a bitmap. This is more space-efficient, improves loading times, etc.

OTHER TIPS

i assume this won't occur for 9-patch images, right? also, when using the image file, will extracting the apk file still show the image file inside it?

anyway, i'm not sure if that helps, but have you tried to check this value:

TypedValue value = a.peekValue(R.styleable.CustomView_src);

then , if it's any of the color types, you can create your own drawable with this color. problem is how to get the size if that's what you get.

however, if in the special case you've shown, you get a reference type, you can probably force it to be BitmapDrawable by just creating the bitmap using BitmapFactory.decodeResource().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top