Creating a bitmap from a drawing

I will be working on an application that requires drag and drop to Canvas

. Basically, I want to take ShapeDrawable

and convert it to Bitmap

one that I can make the user drag around the screen. This is a simple exercise in itself.

However, I want to add some text inside my shape. Is there a way to add some text to itself drawable

and then convert to a bitmap? I considered creating TextView

with the ability to draw as a background.

Is this the best way to do it? I kind of want to avoid creation TextViews

in my code. Any advice is appreciated.

Edit 2/21/2013:

In response to JustDanyul's post, I have the following code:

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

      

My drawable doesn't appear when I draw a bitmap on another canvas. The selectable itself is fine (I tested it as a background for a TextView). The text will appear. Am I missing something in this code?

<?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>

      

Edit # 2 2/21/2013:

I added:

shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());

      

into my code and now the drawable appears, but my text is gone (or just hidden).

+3


source to share


1 answer


I would suggest you try something like this, firstly, create an empty bitmap:

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

      

Next step, create a new canvas instance that maps to your newly created bitmap

Canvas canvas = new Canvas(bitmap);

      



Now you can draw a ShapeDrawable onto an empty bitmap using the Draw ShapeDrawable method

myshapedrawable.draw(canvas);

      

Finally, you can use the drawText method of the canvas instance to draw your text to the canvas.

+3


source







All Articles