将旋转的 drawable 设置为 TextView 的 drawableLeft

Set rotated drawable as TextView's drawableLeft

我想在 TextView 中旋转 drawableLeft。

我试过这段代码:

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);
}

但它在左侧可绘制对象的位置给我一个空白 space。

实际上,即使是最简单的代码也会给出空白 space:

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

这个很好用:

 setCompoundDrawables(originalDrawable, null, null, null);

你不能只"cast"一个Drawable到一个BitmapDrawable

要将 Drawable 转换为 Bitmap,您必须 "draw" 它,如下所示:

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);

在此处查看 post:

How to convert a Drawable to a Bitmap?

根据the docs, if you want to set drawableLeft you should call setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)。只有在 Drawable 上调用了 setBounds() 时,调用 setCompoundDrawables() 才有效,这可能就是您的 originalDrawable 有效的原因。

因此将您的代码更改为:

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