Android drawText including text wrapping

Mustafa Nasser picture Mustafa Nasser · Aug 27, 2013 · Viewed 14.9k times · Source

I am currently creating an image editor and am attempting to draw text on top of on image using canvas.drawText(). So far I have been successful in doing this but when the user enters text that is too long, the text just continues on one line out of the page and doesn't wrap itself to the width of the screen. How would I go about doing this? I have tried using a static layout but cannot seem to get it to work, has anyone got a tutorial to do this?

My function for drawing on a canvas using static layout:

 public Bitmap createImage(float scr_x,float scr_y,String user_text){

            Canvas canvas = new Canvas(image);

            scr_x = 100;
            scr_y = 100;
            final TextPaint tp = new TextPaint(Color.WHITE);     
            canvas.save();
            StaticLayout sl = new StaticLayout("" + user_text, tp, originalBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            sl.draw(canvas);

         return image;
        }

Okay, I've updated my code, but when I try to draw on the image nothing happens at all, I have no idea why either:

    public Bitmap createImage(String user_text) {
    // canvas object with bitmap image as constructor
    Canvas canvas = new Canvas(image);
    TextPaint tp = new TextPaint();
    tp.setColor(Color.RED);
    tp.setTextSize(50);
    tp.setTextAlign(Align.CENTER);
    tp.setAntiAlias(true);
    StaticLayout sl = new StaticLayout("" + user_text, tp,
            canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
    canvas.translate(100, 100);
    sl.draw(canvas);
    return image;
}

Is staticlayout not meant to be used to draw on canvas?

Answer

Lisa Wray picture Lisa Wray · Aug 29, 2013

Yes, StaticLayout is what you're meant to use to draw multi-line text on a Canvas. Save yourself a world of pain and don't think about breaking text yourself -- you're on the right path.

I'm not sure about the bitmap problem, but your second code above worked just fine to draw text on a canvas for me.

Learn to use StaticLayout , then draw the Layout object onto a canvas using the Layout.draw() method.

References