9

I want to rotate drawableLeft in a TextView.

I tried this code:

Drawable result = rotate(degree);
setCompoundDrawables(result, null, null, null);

private Drawable rotate(int degree)
{
    Bitmap iconBitmap = ((BitmapDrawable)originalDrawable).getBitmap();

    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    Bitmap targetBitmap = Bitmap.createBitmap(iconBitmap, 0, 0, iconBitmap.getWidth(), iconBitmap.getHeight(), matrix, true);

    return new BitmapDrawable(getResources(), targetBitmap);
}

But it gives me a blank space on the left drawable's place.

Actually, even this simplest code gives blank space:

Bitmap iconBitmap = ((BitmapDrawable)originalDrawable).getBitmap();
Drawable result = new BitmapDrawable(getResources(), iconBitmap);
setCompoundDrawables(result, null, null, null);

This one works fine:

 setCompoundDrawables(originalDrawable, null, null, null);
TpoM6oH
  • 8,385
  • 3
  • 40
  • 72

2 Answers2

5

According to the docs, if you want to set drawableLeft you should call setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom). Calling setCompoundDrawables() only works if setBounds() has been called on the Drawable, which is probably why your originalDrawable works.

So change your code to:

Drawable result = rotate(degree);
setCompoundDrawablesWithIntrinsicBounds(result, null, null, null);
samgak
  • 23,944
  • 4
  • 60
  • 82
0

You can't just "cast" a Drawable to a BitmapDrawable

To convert a Drawable to a Bitmap you have to "draw" it, like this:

Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); 
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

See the post here:

How to convert a Drawable to a Bitmap?

Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36
  • Yes, I know, I ignored it to make the example simpler. I use this code to convert a drawable if it is not a BitmapDrawable. – TpoM6oH Jan 15 '15 at 14:10
  • You should post the code that you actually use - if you have a bug that you can't find, then you might "simplify" the bug out of your code. Also, it wastes people's time to post pseudo-code unless you state that you are doing so, like what just happened... – Jim Jan 15 '15 at 14:12
  • Sorry about that, I will do so next time. – TpoM6oH Jan 15 '15 at 14:15