将旋转的可绘制对象设置为TextView的drawableLeft

9

我希望可以在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类即可。 - pskink
2个回答

5

0

你不能直接将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);

请查看此帖子:

如何将Drawable转换为Bitmap?


是的,我知道,为了让示例更简单,我忽略了它。如果一个可绘制对象不是BitmapDrawable,我使用这段代码进行转换。 - TpoM6oH
你应该发布你实际使用的代码 - 如果你有一个找不到错误的bug,那么你可能会将这个bug从你的代码中“简化”掉。此外,如果你没有声明正在使用伪代码,那么发布伪代码会浪费人们的时间,就像刚刚发生的事情一样... - Jim
抱歉,下次我会注意的。 - TpoM6oH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接