Draw StaticLayout Text Including HTML Code In An Android Canvas

- 1 answer

Let a multiline HTML text like this one: <div style="color: red;"><b>foo</b></div>. It can be multiline because at least one of these conditions is true: a) the text is very long or b) there is at least one <br />.

The aim is to draw this text in a canvas, which is constructed using a Bitmap.

The minimal code I have written is the following (,

private BitmapDrawable addTextOnImage(BitmapDrawable bitmapDrawable) {
    Bitmap bitmap = ...;
    String caption = rich_editor_caption.getHtml();
    StaticLayout mTextLayout_caption = StaticLayout.Builder.obtain(caption, 0, caption.length(), mTextPaint, bitmap.getWidth()).build();
    Bitmap final_bitmap = Bitmap.createBitmap(bitmap.getWidth(), mTextLayout_caption.getHeight() + bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(final_bitmap);
    return new BitmapDrawable(getActivity().getResources(), final_bitmap);

If the variable caption contains HTML code, the latter won't be interpreted. In other words: the tags will actually be shown in the resulting image.

Is it possible to make the Android app interpret this code?



StaticLayout.Builder.obtain.obtain(caption, 0, caption.length(), mTextPaint, bitmap.getWidth()).build() ;

In the doc, the first parameter is "source CharSequence: The text to be laid out, optionally with spans This value must never be null. " (

So don't pass it a string of the html code, but a charsequence with spans that represent the interpreted html. For this purpose one should use Html.fromHtml (,%20int)).

Note: this answer is incomplete: HTML like <b style="color: rgb(255, 0, 0);">Rrr</b> will be interpreted without color, even if the flag Html.FROM_HTML_OPTION_USE_CSS_COLORS is used.