2012-08-03 168 views
0

我有一个带描边的XML可绘制文件,我也有几个位图我想要应用笔触。我试着打电话Drawable.draw(画布),但它抛出IllegalStateException异常将Drawable绘制到位图

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

我应该怎么办呢?

+0

你能显示完整的logcat的吗? – Eric 2012-08-04 00:08:31

+0

傻我。仔细阅读logcat后,这是因为位图是不可变的。我只是添加了'bmp1.copy()',它不会再抛出异常,尽管笔画不可见(可能绘制在位图的边界之外)。 – garbagecollector 2012-08-04 00:27:30

+0

您可以尝试[''](http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape)技术。如果失败了,您可能需要根据画布的大小手动调整'Bitmap'的大小。 – Eric 2012-08-04 00:30:40

回答

2

解决方案:

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;