1. Overview
Recent projects have new requirements, ued gave a card voucher password UI style,
I see very simple ah, a textview solve the problem, and then do in the simulator after a look .....
Nani, this time just remembered, TextView Chinese and English together will have typesetting problem, how to solve it ...
Ideas
The beginning of the idea is a character of a character to draw, draw to the right critical point on the line to draw, the results of the practice later found different characters between the gap between the display will be very messy, and there is no good solution to this spacing problem, so this program pass;
Single-character drawing No, that's a line of paint, split the text into n lines according to the length of the view, and then draw one line at a line.
2. Implement
First create a autowraptextview that inherits from view
The Initstyle method and the Initpaint method are called respectively in the Init method;
The Initstyle method primarily resolves custom properties
The property name meaning is obviously not too much to explain, the Initpaint method is to initialize a text brush
Let's take a look at how to set the text SetText method
First, convert the text into a char array, and then loop the array to split the entire text into n lines of text, below to see the core method Splittext method
First, create a list collection with the property named Msplittextlist to hold the split text;
Msingletextwidth the width of the single-line text display;
Currentsingletextwidth the width of the accumulated calculation for the current row;
Then start looping the char array, the Getsinglecharwidth method is to calculate the width of a single char;
If Currentsingletextwidth is less than msingletextwidth, add char to Linestringbuffer, If it is the last char, add the Linestringbuffer directly to the Msplittextlist collection
If the currentsingletextwidth is greater than msingletextwidth, add the Linestringbuffer to the Msplittextlist collection and re-assign the value to Linestringbuffer, Currentsingletextwidth 0;
After the loop is finished, the text that is split is added to the Msplittextlist collection.
After the split is complete, loop msplittextlist collection, get the RECT value of each line text, use it when drawing, and then set the view width height.
Next is the drawing method DrawText
First get the height of the first line of text from the top margintop, and then loop through the text to draw each of the contents.
Let's take a look at the final effect.
At this point the entire class of logical analysis is over, want to see the full source can be:
Https://github.com/chenpengfei88/AutoWrapTextView
Android Autowraptextview solve Chinese and English typesetting problems