androidandroid-canvasstaticlayout

Draw StaticLayout text including HTML code in an Android canvas


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 (android.graphics.Canvas, android.graphics.drawable.BitmapDrawable...):

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);
    mTextLayout_caption.draw(canvas);
    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?


Solution

  • 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. " ( https://developer.android.com/reference/kotlin/android/text/StaticLayout.Builder#obtain)

    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 ( https://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String,%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.