昨天看完CCLabel里面文本根据dimension的自动换行功能,刚开始觉得很多部分都是坑,槽点太多,今天再回顾看一遍,发现虽然问题还是有,但有几个部分总算明白为什么是那么个写法了~
致歉……
通过 CCLabel.makeLabel 静态方法得到一个实体,之后可以传入一个dimension (CGSize 类型) 参数来指定文本绘制的大小。
槽点继续:
槽点1:假如你要显示的是中文,so sorry. 这个方法不适合你。
槽点2:cocos2d-x 可以通过传入(XXX,0) 来指定自动调整Label的高度。但你就不能这样~
槽点3:假如你不知道怎么强制换行,试试将'\n'换成' '(空格),不保证有用哈。至于原因,请看下面逻辑
逻辑整理:
原(针对英文的自动换行):将字符串根据' '切割成N个单词,再遍历所有单词逐个进行拼接。如果这个单词接上去之后该行的宽度不超过dimension的宽度,那么这个单词就接上去,否则这个单词另起一行。 也就是说,这个自动换行功能没有像遇到\n就强制换行的功能(除非你自己再去实现下)。
改(针对中文的自动换行):将字符串根据\n切割成N行,再遍历每一行,如果该行宽度超过dimension的宽度,则保留不大于dimension宽度的字符串,剩余字符串另起一行。
特别奉送(中文字符串自动换行):
protected ArrayList<String> wrapText(Paint textPaint, String text, float width) {
/*
* the role is:
* 1.Split lines by '\n'.
* 2.Add a new line if length of word is larger than width.
*
* *** note:This method is useful for Chinese, but not for English.
*/
ArrayList<String> lines = new ArrayList<String>();
String[] words = text.split("\n");
for (String word : words) {
float wordWidth = textPaint.measureText(word);
if (wordWidth < width) {
lines.add(word);
} else {
int i = word.length() - 1;
for (; i >= 0; i--) {
wordWidth = textPaint.measureText(word, 0, i);
if (wordWidth < width) {
break;
}
}
if (i > 0) {
lines.add(word.substring(0, i));
lines.add(word.substring(i, word.length()));
} else {
lines.add(word);
}
}
}
return lines;
}