Frost Lau
Frost Lau

Reputation: 53

Android Canvas drawText with SpannableString

I made a custom View using Canvas.drawText() to draw some SpannableStrings.

I call SpannableString.setSpan() when the text contains emoji I made(I don't like the default-style emoji). I found the Canvas.drawText() does not draw the span I set and instead, it draws the default-style emoji. I tried to call TextView.setText() passing the same SpannableString and it works. I want to use Canvas to draw the text for performance(Otherwise, newing several TextViews while scrolling in ListView causes severe problem about performance). How can I draw SpannableString with Canvas?

Sorry for my poor English, I am not a native speaker. Thanks for advance!

EDIT: Actually I made this custom View in order to show animation of text transitions. Several texts will go across the screen horizontally. The problem I met is that the TextView's draw method causes too much time and the animation looks bad. So I want to draw the text directly using Canvas. Sadly, I switched to StaticLayout and still found the animation is jerky.

Upvotes: 3

Views: 2916

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19417

You could try adding your Spannable to a StaticLayout and draw that to a Canvas.

Something like this:

StaticLayout layout = new StaticLayout(yourSpannable, yourPaint,
        yourCanvas.getWidth(), Alignment.ALIGN_NORMAL, 1, 0, false);
layout.draw(yourCanvas);

Upvotes: 5

Related Questions