从可绘制对象创建位图

3
我将要开发一个需要在画布上拖放的应用程序。基本上,我想要将一个ShapeDrawable转换为Bitmap,以便用户可以在屏幕上拖动它。这本身就是一个简单的练习。
然而,我希望在我的形状内部添加文本。有没有办法将文本添加到drawable本身,然后再转换为位图?我尝试创建一个TextView,并将drawable作为背景,但是这是最好的方法吗?我有点想避免在代码中创建TextViews。感谢任何建议。
编辑2/21/2013:根据JustDanyul的帖子,我有以下代码:
int width = 40;
int height = 40;
Bitmap.Config config = Bitmap.Config.ARGB_8888;
bitmap = Bitmap.createBitmap(width, height, config);
Canvas canvas = new Canvas(bitmap);
Resources res = context.getResources();
Drawable shape = res.getDrawable(R.drawable.miss_scarlet);
shape.draw(canvas);
Paint paint = new Paint();
paint.setTextSize(fontSize);
paint.setColor(Color.BLACK);
canvas.drawText(gameToken.getDbName(), 5, 5, paint);

在我将位图绘制到另一个画布上时,我的可绘制对象没有显示出来。 可绘制对象本身是正常的(我已将其作为TextView的背景进行测试)。 文本正常显示。 我在这段代码中漏掉了什么吗?

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="4dp" />
    <solid
        android:color="#FF0000" />
    <stroke
        android:width="3dp"
        android:color="#000000" />
</shape>

编辑 #2 2013年2月21日:
我添加了:
shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());

我更新了我的代码,现在可绘制的图形出现了,但我的文本消失了(或者只是隐藏了)。


shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); 解决了我的问题。谢谢。 - Ajay
1个回答

3

我建议您尝试以下方法,首先创建一个空位图:

int w = 500  
int h = 500; // or whatever sizes you need
Bitmap.Config config = Bitmap.Config.ARGB_8888;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);

下一步是创建一个新的画布实例,将其渲染到您新创建的位图上。
Canvas canvas = new Canvas(bitmap);

现在,您可以使用ShapeDrawable的绘制方法将ShapeDrawable绘制到空位图上。
myshapedrawable.draw(canvas);

最后,您可以使用画布实例的drawText方法在画布上绘制文本。

这将为“XML中的形状”添加shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());,否则将无法正常工作。 - Ajay

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