9

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.

Naruto Uzumaki
  • 2,019
  • 18
  • 37
  • Paint already has methods to format the text like under lining, applying the colors... So you can use them to format your text instead of html tags – Chandrakanth Feb 24 '15 at 08:29
  • Instead of `drawText` I think you shoul use `Layout.draw()`, it accepts `HTML`, here you are more information about [DynamicLayout](http://developer.android.com/reference/android/text/DynamicLayout.html) – Skizo-ozᴉʞS ツ Feb 24 '15 at 08:31
  • @Chandrakanth tnx for answer, Can u provide an example? – Naruto Uzumaki Feb 24 '15 at 09:26
  • 1
    @Skizo tnx, But what is Layout in this case? – Naruto Uzumaki Feb 24 '15 at 09:27
  • @Naruto I'm not sure if there's a simpler way, but I just ran a test that loaded some HTML in an off-screen WebView to render it, then drew the WebView to a Canvas. Might be a usable workaround, if you don't find a better way. – Mike M. Feb 26 '15 at 11:03
  • @MikeM. tnx. but I have some problem with `WebView`. It cannot support arabic letters. – Naruto Uzumaki Feb 26 '15 at 22:01
  • @NarutoUzumaki Interesting. I was not aware of that. Thanks for the info! – Mike M. Feb 26 '15 at 23:45
  • As mentioned in the above comments, we may use Dynamic or Static Layout. Instead of String we need to use Spannable text. This can handle html tags. You may find the example here https://stackoverflow.com/a/10410843/2641380 – SHS Aug 24 '17 at 09:03

2 Answers2

4

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);
Alen Lee
  • 2,479
  • 2
  • 21
  • 30
-4

If you want under line text then you can write like this

    TextPaint textPaint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setFlags(TextPaint.UNDERLINE_TEXT_FLAG);
    textPaint.setColor(Color.WHITE);

    canvas.drawText("Hello", 0, 20, textPaint);
Chandrakanth
  • 3,711
  • 2
  • 18
  • 31
  • I want no only underline, I want support all supported tag, like

    etc... . In my case I passed a full html content to that, which have multiline and multi tag.
    – Naruto Uzumaki Feb 24 '15 at 09:49