Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas draw html text

Is it possible to pass Html to Canvas.drawtext().
I tried this:

canvas.drawText(Html.fromHtml("This is an <u>underline</u> text demo for TextView."), 0, 20, colIndex, rowIndex, getTextPaint());

But that cannot parse tags and not show correctly.

Thanks in advance.

like image 650
Naruto Uzumaki Avatar asked Feb 24 '15 08:02

Naruto Uzumaki


People also ask

How do you put text on a canvas in HTML?

To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.

Can a canvas contain text in HTML?

Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText().


1 Answers

You can parse the html string into Spanned

public static Spanned fromHtml(String html, int flags) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        return Html.fromHtml(html, flags);
    } else {
        return Html.fromHtml(html);
    }
}

then use StaticLayout to draw:

mStaticLayout = new StaticLayout(fromHtml(html, Html.FROM_HTML_MODE_LEGACY), mPaint, sizeWidth, Alignment.ALIGN_NORMAL, 1.0f, 0, false);
like image 119
Alen Lee Avatar answered Sep 22 '22 08:09

Alen Lee