CCLabelTextFormatter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /****************************************************************************
  2. Copyright (c) 2013 Zynga Inc.
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "2d/CCLabel.h"
  23. #include <vector>
  24. #include "base/ccUTF8.h"
  25. #include "base/CCDirector.h"
  26. #include "2d/CCFontAtlas.h"
  27. #include "2d/CCFontFNT.h"
  28. NS_CC_BEGIN
  29. void Label::computeAlignmentOffset()
  30. {
  31. _linesOffsetX.clear();
  32. switch (_hAlignment)
  33. {
  34. case cocos2d::TextHAlignment::LEFT:
  35. _linesOffsetX.assign(_numberOfLines, 0);
  36. break;
  37. case cocos2d::TextHAlignment::CENTER:
  38. for (auto lineWidth : _linesWidth)
  39. {
  40. _linesOffsetX.push_back((_contentSize.width - lineWidth) / 2.f);
  41. }
  42. break;
  43. case cocos2d::TextHAlignment::RIGHT:
  44. for (auto lineWidth : _linesWidth)
  45. {
  46. _linesOffsetX.push_back(_contentSize.width - lineWidth);
  47. }
  48. break;
  49. default:
  50. break;
  51. }
  52. switch (_vAlignment)
  53. {
  54. case cocos2d::TextVAlignment::TOP:
  55. _letterOffsetY = _contentSize.height;
  56. break;
  57. case cocos2d::TextVAlignment::CENTER:
  58. _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2.f;
  59. break;
  60. case cocos2d::TextVAlignment::BOTTOM:
  61. _letterOffsetY = _textDesiredHeight;
  62. break;
  63. default:
  64. break;
  65. }
  66. }
  67. int Label::getFirstCharLen(const std::u32string& /*utf32Text*/, int /*startIndex*/, int /*textLen*/) const
  68. {
  69. return 1;
  70. }
  71. int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int textLen) const
  72. {
  73. int len = 0;
  74. auto nextLetterX = 0;
  75. FontLetterDefinition letterDef;
  76. auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();
  77. for (int index = startIndex; index < textLen; ++index)
  78. {
  79. char32_t character = utf32Text[index];
  80. if (character == StringUtils::UnicodeCharacters::NewLine
  81. || (!StringUtils::isUnicodeNonBreaking(character)
  82. && (StringUtils::isUnicodeSpace(character)
  83. || StringUtils::isCJKUnicode(character))))
  84. {
  85. break;
  86. }
  87. if (!getFontLetterDef(character, letterDef))
  88. {
  89. break;
  90. }
  91. if (_maxLineWidth > 0.f)
  92. {
  93. auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;
  94. if (letterX + letterDef.width * _bmfontScale > _maxLineWidth)
  95. break;
  96. }
  97. nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;
  98. len++;
  99. }
  100. if (len == 0 && textLen)
  101. len = 1;
  102. return len;
  103. }
  104. bool Label::getFontLetterDef(char32_t character, FontLetterDefinition& letterDef) const
  105. {
  106. if (character == StringUtils::UnicodeCharacters::NoBreakSpace)
  107. {
  108. // change no-break space to regular space
  109. // reason: some fonts have issue with no-break space:
  110. // * no letter definition
  111. // * not normal big width
  112. character = StringUtils::UnicodeCharacters::Space;
  113. }
  114. return _fontAtlas->getLetterDefinitionForChar(character, letterDef);
  115. }
  116. void Label::updateBMFontScale()
  117. {
  118. auto font = _fontAtlas->getFont();
  119. if (_currentLabelType == LabelType::BMFONT) {
  120. FontFNT *bmFont = (FontFNT*)font;
  121. float originalFontSize = bmFont->getOriginalFontSize();
  122. _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize;
  123. }else{
  124. _bmfontScale = 1.0f;
  125. }
  126. }
  127. bool Label::multilineTextWrap(const std::function<int(const std::u32string&, int, int)>& nextTokenLen)
  128. {
  129. int textLen = getStringLength();
  130. int lineIndex = 0;
  131. float nextTokenX = 0.f;
  132. float nextTokenY = 0.f;
  133. float longestLine = 0.f;
  134. float letterRight = 0.f;
  135. auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();
  136. float lineSpacing = _lineSpacing * contentScaleFactor;
  137. float highestY = 0.f;
  138. float lowestY = 0.f;
  139. FontLetterDefinition letterDef;
  140. Vec2 letterPosition;
  141. bool nextChangeSize = true;
  142. this->updateBMFontScale();
  143. for (int index = 0; index < textLen; )
  144. {
  145. char32_t character = _utf32Text[index];
  146. if (character == StringUtils::UnicodeCharacters::NewLine)
  147. {
  148. _linesWidth.push_back(letterRight);
  149. letterRight = 0.f;
  150. lineIndex++;
  151. nextTokenX = 0.f;
  152. nextTokenY -= _lineHeight*_bmfontScale + lineSpacing;
  153. recordPlaceholderInfo(index, character);
  154. index++;
  155. continue;
  156. }
  157. auto tokenLen = nextTokenLen(_utf32Text, index, textLen);
  158. float tokenHighestY = highestY;
  159. float tokenLowestY = lowestY;
  160. float tokenRight = letterRight;
  161. float nextLetterX = nextTokenX;
  162. bool newLine = false;
  163. for (int tmp = 0; tmp < tokenLen;++tmp)
  164. {
  165. int letterIndex = index + tmp;
  166. character = _utf32Text[letterIndex];
  167. if (character == StringUtils::UnicodeCharacters::CarriageReturn)
  168. {
  169. recordPlaceholderInfo(letterIndex, character);
  170. continue;
  171. }
  172. // \b - Next char not change x position
  173. if (character == StringUtils::UnicodeCharacters::NextCharNoChangeX)
  174. {
  175. nextChangeSize = false;
  176. recordPlaceholderInfo(letterIndex, character);
  177. continue;
  178. }
  179. if (!getFontLetterDef(character, letterDef))
  180. {
  181. recordPlaceholderInfo(letterIndex, character);
  182. CCLOG("LabelTextFormatter error: can't find letter definition in font file for letter: 0x%x", character);
  183. continue;
  184. }
  185. auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;
  186. if (_enableWrap && _maxLineWidth > 0.f && nextTokenX > 0.f && letterX + letterDef.width * _bmfontScale > _maxLineWidth
  187. && !StringUtils::isUnicodeSpace(character) && nextChangeSize)
  188. {
  189. _linesWidth.push_back(letterRight);
  190. letterRight = 0.f;
  191. lineIndex++;
  192. nextTokenX = 0.f;
  193. nextTokenY -= (_lineHeight*_bmfontScale + lineSpacing);
  194. newLine = true;
  195. break;
  196. }
  197. else
  198. {
  199. letterPosition.x = letterX;
  200. }
  201. letterPosition.y = (nextTokenY - letterDef.offsetY * _bmfontScale) / contentScaleFactor;
  202. recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
  203. if (nextChangeSize)
  204. {
  205. if (_horizontalKernings && letterIndex < textLen - 1)
  206. nextLetterX += _horizontalKernings[letterIndex + 1];
  207. nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;
  208. if (tokenLen != 1 || !StringUtils::isUnicodeSpace(character))
  209. {
  210. tokenRight = nextLetterX / contentScaleFactor;
  211. }
  212. }
  213. nextChangeSize = true;
  214. if (tokenHighestY < letterPosition.y)
  215. tokenHighestY = letterPosition.y;
  216. if (tokenLowestY > letterPosition.y - letterDef.height * _bmfontScale)
  217. tokenLowestY = letterPosition.y - letterDef.height * _bmfontScale;
  218. }
  219. if (newLine)
  220. {
  221. continue;
  222. }
  223. nextTokenX = nextLetterX;
  224. letterRight = tokenRight;
  225. if (highestY < tokenHighestY)
  226. highestY = tokenHighestY;
  227. if (lowestY > tokenLowestY)
  228. lowestY = tokenLowestY;
  229. if (longestLine < letterRight)
  230. longestLine = letterRight;
  231. index += tokenLen;
  232. }
  233. _linesWidth.push_back(letterRight);
  234. _numberOfLines = lineIndex + 1;
  235. _textDesiredHeight = (_numberOfLines * _lineHeight * _bmfontScale) / contentScaleFactor;
  236. if (_numberOfLines > 1)
  237. _textDesiredHeight += (_numberOfLines - 1) * _lineSpacing;
  238. Size contentSize(_labelWidth, _labelHeight);
  239. if (_labelWidth <= 0.f)
  240. contentSize.width = longestLine;
  241. if (_labelHeight <= 0.f)
  242. contentSize.height = _textDesiredHeight;
  243. setContentSize(contentSize);
  244. _tailoredTopY = contentSize.height;
  245. _tailoredBottomY = 0.f;
  246. if (highestY > 0.f)
  247. _tailoredTopY = contentSize.height + highestY;
  248. if (lowestY < -_textDesiredHeight)
  249. _tailoredBottomY = _textDesiredHeight + lowestY;
  250. return true;
  251. }
  252. bool Label::multilineTextWrapByWord()
  253. {
  254. return multilineTextWrap(CC_CALLBACK_3(Label::getFirstWordLen, this));
  255. }
  256. bool Label::multilineTextWrapByChar()
  257. {
  258. return multilineTextWrap(CC_CALLBACK_3(Label::getFirstCharLen, this));
  259. }
  260. bool Label::isVerticalClamp()
  261. {
  262. if (_textDesiredHeight > _contentSize.height)
  263. {
  264. return true;
  265. }
  266. else
  267. {
  268. return false;
  269. }
  270. }
  271. bool Label::isHorizontalClamp()
  272. {
  273. bool letterClamp = false;
  274. for (int ctr = 0; ctr < _lengthOfString; ++ctr)
  275. {
  276. if (_lettersInfo[ctr].valid)
  277. {
  278. auto& letterDef = _fontAtlas->_letterDefinitions[_lettersInfo[ctr].utf32Char];
  279. auto px = _lettersInfo[ctr].positionX + letterDef.width/2 * _bmfontScale;
  280. auto lineIndex = _lettersInfo[ctr].lineIndex;
  281. if(_labelWidth > 0.f){
  282. if(!this->_enableWrap){
  283. if (px > _contentSize.width) {
  284. letterClamp = true;
  285. break;
  286. }
  287. }
  288. else{
  289. auto wordWidth = this->_linesWidth[lineIndex];
  290. if(wordWidth > this->_contentSize.width && (px > _contentSize.width)){
  291. letterClamp = true;
  292. break;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. return letterClamp;
  299. }
  300. void Label::shrinkLabelToContentSize(const std::function<bool(void)>& lambda)
  301. {
  302. float fontSize = this->getRenderingFontSize();
  303. int i = 0;
  304. auto letterDefinition = _fontAtlas->_letterDefinitions;
  305. auto tempLetterDefinition = letterDefinition;
  306. float originalLineHeight = _lineHeight;
  307. bool flag = true;
  308. while (lambda()) {
  309. ++i;
  310. float newFontSize = fontSize - i;
  311. flag = false;
  312. if (newFontSize <= 0) {
  313. break;
  314. }
  315. float scale = newFontSize / fontSize;
  316. std::swap(_fontAtlas->_letterDefinitions, tempLetterDefinition);
  317. _fontAtlas->scaleFontLetterDefinition(scale);
  318. this->setLineHeight(originalLineHeight * scale);
  319. if (_maxLineWidth > 0.f && !_lineBreakWithoutSpaces)
  320. {
  321. multilineTextWrapByWord();
  322. }
  323. else
  324. {
  325. multilineTextWrapByChar();
  326. }
  327. computeAlignmentOffset();
  328. tempLetterDefinition = letterDefinition;
  329. }
  330. this->setLineHeight(originalLineHeight);
  331. std::swap(_fontAtlas->_letterDefinitions, letterDefinition);
  332. if (!flag) {
  333. if (fontSize - i >= 0) {
  334. this->scaleFontSizeDown(fontSize - i);
  335. }
  336. }
  337. }
  338. void Label::recordLetterInfo(const cocos2d::Vec2& point, char32_t utf32Char, int letterIndex, int lineIndex)
  339. {
  340. if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
  341. {
  342. LetterInfo tmpInfo;
  343. _lettersInfo.push_back(tmpInfo);
  344. }
  345. _lettersInfo[letterIndex].lineIndex = lineIndex;
  346. _lettersInfo[letterIndex].utf32Char = utf32Char;
  347. _lettersInfo[letterIndex].valid = _fontAtlas->_letterDefinitions[utf32Char].validDefinition;
  348. _lettersInfo[letterIndex].positionX = point.x;
  349. _lettersInfo[letterIndex].positionY = point.y;
  350. _lettersInfo[letterIndex].atlasIndex = -1;
  351. }
  352. void Label::recordPlaceholderInfo(int letterIndex, char32_t utf32Char)
  353. {
  354. if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
  355. {
  356. LetterInfo tmpInfo;
  357. _lettersInfo.push_back(tmpInfo);
  358. }
  359. _lettersInfo[letterIndex].utf32Char = utf32Char;
  360. _lettersInfo[letterIndex].valid = false;
  361. }
  362. NS_CC_END