【问题标题】:Set rotated drawable as TextView's drawableLeft将旋转的drawable设置为TextView的drawableLeft
【发布时间】:2015-01-15 22:21:35
【问题描述】:

我想在 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);
}

但它在左侧可绘制的地方给了我一个空白空间。

实际上,即使是最简单的代码也会出现空格:

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

这个很好用:

 setCompoundDrawables(originalDrawable, null, null, null);

【问题讨论】:

  • 你想旋转 Drawable 吗?只需使用 RotateDrawable 类

标签: android image


【解决方案1】:

根据the docs,如果你想设置drawableLeft,你应该调用setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)。仅当在 Drawable 上调用 setBounds() 时调用 setCompoundDrawables() 才有效,这可能是您 originalDrawable 有效的原因。

所以把你的代码改成:

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

【讨论】:

    【解决方案2】:

    您不能只是将Drawable“转换”为BitmapDrawable

    要将 Drawable 转换为 Bitmap,您必须“绘制”它,如下所示:

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

    在此处查看帖子:

    How to convert a Drawable to a Bitmap?

    【讨论】:

    • 是的,我知道,我忽略了它以使示例更简单。如果它不是 BitmapDrawable,我使用此代码转换可绘制对象。
    • 你应该发布你实际使用的代码——如果你有一个你找不到的错误,那么你可以“简化”你的代码中的错误。此外,除非您声明您正在这样做,否则发布伪代码会浪费人们的时间,就像刚刚发生的那样......
    • 对不起,我下次再做。