3

I am going to be working on an app which requires drag/drop on a Canvas. Basically, I want to take a ShapeDrawable and convert it into a Bitmap which I can have the user drag around the screen. This is a simple exercise in itself.

However, I want to add text inside my shape. Is there a way I can add text to the drawable itself then convert to a bitmap? I looked into creating a TextView with a drawable as a background.

Is this the best way to do it? I sort of want to avoid creating 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 is not showing up when I draw the bitmap on another canvas. The drawable itself is fine (I tested it as a background to a TextView). The text shows up. 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());

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

1
  • shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); resolved my problem. Thanks Commented Jul 23, 2014 at 10:26

1 Answer 1

3

I would suggest you to try something like this, first, 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, which renders onto your newly created bitmap

Canvas canvas = new Canvas(bitmap);

Now, you can draw the ShapeDrawable onto your empty bitmap using the ShapeDrawable's draw method

myshapedrawable.draw(canvas);

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

Sign up to request clarification or add additional context in comments.

1 Comment

this would add shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); for "Shape in xml" specially otherwise will not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.