将Drawable绘制为位图

时间:2012-08-03 23:55:56

标签: android bitmap drawable

我有一个带有笔划的XML可绘制文件,我还有几个位图,我想将笔划应用到。我尝试调用Drawable.draw(canvas),但它抛出IllegalStateException

笔划XML:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <stroke android:width="3dp"
            android:color="#ffffffff"/>
</shape>

绘图代码:

Drawable strokeDrawable = getResources().getDrawable(R.drawable.stroke);
Bitmap bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.bmp1);
Canvas canvas = new Canvas(bmp1);
strokeDrawable.draw(canvas);

我该怎么做?

1 个答案:

答案 0 :(得分:3)

解决方案:

final int STROKE_WIDTH = 3;
Bitmap copy = Bitmap.createBitmap(bmp1.getWidth() + STROKE_WIDTH * 2, bmp1.getHeight() + STROKE_WIDTH * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(copy);
strokeDrawable.setBounds(0, 0, copy.getWidth(), copy.getHeight());
strokeDrawable.draw(canvas);
canvas.drawBitmap(bmp1, STROKE_WIDTH, STROKE_WIDTH, null);
bmp1.recycle();
bmp1 = copy;