YYTextLayout.m 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407
  1. //
  2. // YYTextLayout.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 15/3/3.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "YYTextLayout.h"
  12. #import "YYKitMacro.h"
  13. #import "YYCGUtilities.h"
  14. #import "YYTextUtilities.h"
  15. #import "YYTextAttribute.h"
  16. #import "YYTextArchiver.h"
  17. #import "NSAttributedString+YYText.h"
  18. #import "UIFont+YYAdd.h"
  19. const CGSize YYTextContainerMaxSize = (CGSize){0x100000, 0x100000};
  20. typedef struct {
  21. CGFloat head;
  22. CGFloat foot;
  23. } YYRowEdge;
  24. static inline CGSize YYTextClipCGSize(CGSize size) {
  25. if (size.width > YYTextContainerMaxSize.width) size.width = YYTextContainerMaxSize.width;
  26. if (size.height > YYTextContainerMaxSize.height) size.height = YYTextContainerMaxSize.height;
  27. return size;
  28. }
  29. static inline UIEdgeInsets UIEdgeInsetRotateVertical(UIEdgeInsets insets) {
  30. UIEdgeInsets one;
  31. one.top = insets.left;
  32. one.left = insets.bottom;
  33. one.bottom = insets.right;
  34. one.right = insets.top;
  35. return one;
  36. }
  37. /**
  38. Sometimes CoreText may convert CGColor to UIColor for `kCTForegroundColorAttributeName`
  39. attribute in iOS7. This should be a bug of CoreText, and may cause crash. Here's a workaround.
  40. */
  41. static CGColorRef YYTextGetCGColor(CGColorRef color) {
  42. static UIColor *defaultColor;
  43. static dispatch_once_t onceToken;
  44. dispatch_once(&onceToken, ^{
  45. defaultColor = [UIColor blackColor];
  46. });
  47. if (!color) return defaultColor.CGColor;
  48. if ([((__bridge NSObject *)color) respondsToSelector:@selector(CGColor)]) {
  49. return ((__bridge UIColor *)color).CGColor;
  50. }
  51. return color;
  52. }
  53. @implementation YYTextLinePositionSimpleModifier
  54. - (void)modifyLines:(NSArray *)lines fromText:(NSAttributedString *)text inContainer:(YYTextContainer *)container {
  55. if (container.verticalForm) {
  56. for (NSUInteger i = 0, max = lines.count; i < max; i++) {
  57. YYTextLine *line = lines[i];
  58. CGPoint pos = line.position;
  59. pos.x = container.size.width - container.insets.right - line.row * _fixedLineHeight - _fixedLineHeight * 0.9;
  60. line.position = pos;
  61. }
  62. } else {
  63. for (NSUInteger i = 0, max = lines.count; i < max; i++) {
  64. YYTextLine *line = lines[i];
  65. CGPoint pos = line.position;
  66. pos.y = line.row * _fixedLineHeight + _fixedLineHeight * 0.9 + container.insets.top;
  67. line.position = pos;
  68. }
  69. }
  70. }
  71. - (id)copyWithZone:(NSZone *)zone {
  72. YYTextLinePositionSimpleModifier *one = [self.class new];
  73. one.fixedLineHeight = _fixedLineHeight;
  74. return one;
  75. }
  76. @end
  77. @implementation YYTextContainer {
  78. @package
  79. BOOL _readonly; ///< used only in YYTextLayout.implementation
  80. dispatch_semaphore_t _lock;
  81. CGSize _size;
  82. UIEdgeInsets _insets;
  83. UIBezierPath *_path;
  84. NSArray *_exclusionPaths;
  85. BOOL _pathFillEvenOdd;
  86. CGFloat _pathLineWidth;
  87. BOOL _verticalForm;
  88. NSUInteger _maximumNumberOfRows;
  89. YYTextTruncationType _truncationType;
  90. NSAttributedString *_truncationToken;
  91. id<YYTextLinePositionModifier> _linePositionModifier;
  92. }
  93. + (instancetype)containerWithSize:(CGSize)size {
  94. return [self containerWithSize:size insets:UIEdgeInsetsZero];
  95. }
  96. + (instancetype)containerWithSize:(CGSize)size insets:(UIEdgeInsets)insets {
  97. YYTextContainer *one = [self new];
  98. one.size = YYTextClipCGSize(size);
  99. one.insets = insets;
  100. return one;
  101. }
  102. + (instancetype)containerWithPath:(UIBezierPath *)path {
  103. YYTextContainer *one = [self new];
  104. one.path = path;
  105. return one;
  106. }
  107. - (instancetype)init {
  108. self = [super init];
  109. if (!self) return nil;
  110. _lock = dispatch_semaphore_create(1);
  111. _pathFillEvenOdd = YES;
  112. return self;
  113. }
  114. - (id)copyWithZone:(NSZone *)zone {
  115. YYTextContainer *one = [self.class new];
  116. dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
  117. one->_size = _size;
  118. one->_insets = _insets;
  119. one->_path = _path;
  120. one->_exclusionPaths = _exclusionPaths.copy;
  121. one->_pathFillEvenOdd = _pathFillEvenOdd;
  122. one->_pathLineWidth = _pathLineWidth;
  123. one->_verticalForm = _verticalForm;
  124. one->_maximumNumberOfRows = _maximumNumberOfRows;
  125. one->_truncationType = _truncationType;
  126. one->_truncationToken = _truncationToken.copy;
  127. one->_linePositionModifier = [(NSObject *)_linePositionModifier copy];
  128. dispatch_semaphore_signal(_lock);
  129. return one;
  130. }
  131. - (id)mutableCopyWithZone:(nullable NSZone *)zone {
  132. return [self copyWithZone:zone];
  133. }
  134. - (void)encodeWithCoder:(NSCoder *)aCoder {
  135. [aCoder encodeObject:[NSValue valueWithCGSize:_size] forKey:@"size"];
  136. [aCoder encodeObject:[NSValue valueWithUIEdgeInsets:_insets] forKey:@"insets"];
  137. [aCoder encodeObject:_path forKey:@"path"];
  138. [aCoder encodeObject:_exclusionPaths forKey:@"exclusionPaths"];
  139. [aCoder encodeBool:_pathFillEvenOdd forKey:@"pathFillEvenOdd"];
  140. [aCoder encodeDouble:_pathLineWidth forKey:@"pathLineWidth"];
  141. [aCoder encodeBool:_verticalForm forKey:@"verticalForm"];
  142. [aCoder encodeInteger:_maximumNumberOfRows forKey:@"maximumNumberOfRows"];
  143. [aCoder encodeInteger:_truncationType forKey:@"truncationType"];
  144. [aCoder encodeObject:_truncationToken forKey:@"truncationToken"];
  145. if ([_linePositionModifier respondsToSelector:@selector(encodeWithCoder:)] &&
  146. [_linePositionModifier respondsToSelector:@selector(initWithCoder:)]) {
  147. [aCoder encodeObject:_linePositionModifier forKey:@"linePositionModifier"];
  148. }
  149. }
  150. - (id)initWithCoder:(NSCoder *)aDecoder {
  151. self = [self init];
  152. _size = ((NSValue *)[aDecoder decodeObjectForKey:@"size"]).CGSizeValue;
  153. _insets = ((NSValue *)[aDecoder decodeObjectForKey:@"insets"]).UIEdgeInsetsValue;
  154. _path = [aDecoder decodeObjectForKey:@"path"];
  155. _exclusionPaths = [aDecoder decodeObjectForKey:@"exclusionPaths"];
  156. _pathFillEvenOdd = [aDecoder decodeBoolForKey:@"pathFillEvenOdd"];
  157. _pathLineWidth = [aDecoder decodeDoubleForKey:@"pathLineWidth"];
  158. _verticalForm = [aDecoder decodeBoolForKey:@"verticalForm"];
  159. _maximumNumberOfRows = [aDecoder decodeIntegerForKey:@"maximumNumberOfRows"];
  160. _truncationType = [aDecoder decodeIntegerForKey:@"truncationType"];
  161. _truncationToken = [aDecoder decodeObjectForKey:@"truncationToken"];
  162. _linePositionModifier = [aDecoder decodeObjectForKey:@"linePositionModifier"];
  163. return self;
  164. }
  165. #define Getter(...) \
  166. dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \
  167. __VA_ARGS__; \
  168. dispatch_semaphore_signal(_lock);
  169. #define Setter(...) \
  170. if (_readonly) { \
  171. @throw [NSException exceptionWithName:NSInternalInconsistencyException \
  172. reason:@"Cannot change the property of the 'container' in 'YYTextLayout'." userInfo:nil]; \
  173. return; \
  174. } \
  175. dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \
  176. __VA_ARGS__; \
  177. dispatch_semaphore_signal(_lock);
  178. - (CGSize)size {
  179. Getter(CGSize size = _size) return size;
  180. }
  181. - (void)setSize:(CGSize)size {
  182. Setter(if(!_path) _size = YYTextClipCGSize(size));
  183. }
  184. - (UIEdgeInsets)insets {
  185. Getter(UIEdgeInsets insets = _insets) return insets;
  186. }
  187. - (void)setInsets:(UIEdgeInsets)insets {
  188. Setter(if(!_path){
  189. if (insets.top < 0) insets.top = 0;
  190. if (insets.left < 0) insets.left = 0;
  191. if (insets.bottom < 0) insets.bottom = 0;
  192. if (insets.right < 0) insets.right = 0;
  193. _insets = insets;
  194. });
  195. }
  196. - (UIBezierPath *)path {
  197. Getter(UIBezierPath *path = _path) return path;
  198. }
  199. - (void)setPath:(UIBezierPath *)path {
  200. Setter(
  201. _path = path.copy;
  202. if (_path) {
  203. CGRect bounds = _path.bounds;
  204. CGSize size = bounds.size;
  205. UIEdgeInsets insets = UIEdgeInsetsZero;
  206. if (bounds.origin.x < 0) size.width += bounds.origin.x;
  207. if (bounds.origin.x > 0) insets.left = bounds.origin.x;
  208. if (bounds.origin.y < 0) size.height += bounds.origin.y;
  209. if (bounds.origin.y > 0) insets.top = bounds.origin.y;
  210. _size = size;
  211. _insets = insets;
  212. }
  213. );
  214. }
  215. - (NSArray *)exclusionPaths {
  216. Getter(NSArray *paths = _exclusionPaths) return paths;
  217. }
  218. - (void)setExclusionPaths:(NSArray *)exclusionPaths {
  219. Setter(_exclusionPaths = exclusionPaths.copy);
  220. }
  221. - (BOOL)isPathFillEvenOdd {
  222. Getter(BOOL is = _pathFillEvenOdd) return is;
  223. }
  224. - (void)setPathFillEvenOdd:(BOOL)pathFillEvenOdd {
  225. Setter(_pathFillEvenOdd = pathFillEvenOdd);
  226. }
  227. - (CGFloat)pathLineWidth {
  228. Getter(CGFloat width = _pathLineWidth) return width;
  229. }
  230. - (void)setPathLineWidth:(CGFloat)pathLineWidth {
  231. Setter(_pathLineWidth = pathLineWidth);
  232. }
  233. - (BOOL)isVerticalForm {
  234. Getter(BOOL v = _verticalForm) return v;
  235. }
  236. - (void)setVerticalForm:(BOOL)verticalForm {
  237. Setter(_verticalForm = verticalForm);
  238. }
  239. - (NSUInteger)maximumNumberOfRows {
  240. Getter(NSUInteger num = _maximumNumberOfRows) return num;
  241. }
  242. - (void)setMaximumNumberOfRows:(NSUInteger)maximumNumberOfRows {
  243. Setter(_maximumNumberOfRows = maximumNumberOfRows);
  244. }
  245. - (YYTextTruncationType)truncationType {
  246. Getter(YYTextTruncationType type = _truncationType) return type;
  247. }
  248. - (void)setTruncationType:(YYTextTruncationType)truncationType {
  249. Setter(_truncationType = truncationType);
  250. }
  251. - (NSAttributedString *)truncationToken {
  252. Getter(NSAttributedString *token = _truncationToken) return token;
  253. }
  254. - (void)setTruncationToken:(NSAttributedString *)truncationToken {
  255. Setter(_truncationToken = truncationToken.copy);
  256. }
  257. - (void)setLinePositionModifier:(id<YYTextLinePositionModifier>)linePositionModifier {
  258. Setter(_linePositionModifier = [(NSObject *)linePositionModifier copy]);
  259. }
  260. - (id<YYTextLinePositionModifier>)linePositionModifier {
  261. Getter(id<YYTextLinePositionModifier> m = _linePositionModifier) return m;
  262. }
  263. #undef Getter
  264. #undef Setter
  265. @end
  266. @interface YYTextLayout ()
  267. @property (nonatomic, readwrite) YYTextContainer *container;
  268. @property (nonatomic, readwrite) NSAttributedString *text;
  269. @property (nonatomic, readwrite) NSRange range;
  270. @property (nonatomic, readwrite) CTFramesetterRef frameSetter;
  271. @property (nonatomic, readwrite) CTFrameRef frame;
  272. @property (nonatomic, readwrite) NSArray *lines;
  273. @property (nonatomic, readwrite) YYTextLine *truncatedLine;
  274. @property (nonatomic, readwrite) NSArray *attachments;
  275. @property (nonatomic, readwrite) NSArray *attachmentRanges;
  276. @property (nonatomic, readwrite) NSArray *attachmentRects;
  277. @property (nonatomic, readwrite) NSSet *attachmentContentsSet;
  278. @property (nonatomic, readwrite) NSUInteger rowCount;
  279. @property (nonatomic, readwrite) NSRange visibleRange;
  280. @property (nonatomic, readwrite) CGRect textBoundingRect;
  281. @property (nonatomic, readwrite) CGSize textBoundingSize;
  282. @property (nonatomic, readwrite) BOOL containsHighlight;
  283. @property (nonatomic, readwrite) BOOL needDrawBlockBorder;
  284. @property (nonatomic, readwrite) BOOL needDrawBackgroundBorder;
  285. @property (nonatomic, readwrite) BOOL needDrawShadow;
  286. @property (nonatomic, readwrite) BOOL needDrawUnderline;
  287. @property (nonatomic, readwrite) BOOL needDrawText;
  288. @property (nonatomic, readwrite) BOOL needDrawAttachment;
  289. @property (nonatomic, readwrite) BOOL needDrawInnerShadow;
  290. @property (nonatomic, readwrite) BOOL needDrawStrikethrough;
  291. @property (nonatomic, readwrite) BOOL needDrawBorder;
  292. @property (nonatomic, assign) NSUInteger *lineRowsIndex;
  293. @property (nonatomic, assign) YYRowEdge *lineRowsEdge; ///< top-left origin
  294. @end
  295. @implementation YYTextLayout
  296. #pragma mark - Layout
  297. - (instancetype)_init {
  298. self = [super init];
  299. return self;
  300. }
  301. + (YYTextLayout *)layoutWithContainerSize:(CGSize)size text:(NSAttributedString *)text {
  302. YYTextContainer *container = [YYTextContainer containerWithSize:size];
  303. return [self layoutWithContainer:container text:text];
  304. }
  305. + (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text {
  306. return [self layoutWithContainer:container text:text range:NSMakeRange(0, text.length)];
  307. }
  308. + (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range {
  309. YYTextLayout *layout = NULL;
  310. CGPathRef cgPath = nil;
  311. CGRect cgPathBox = {0};
  312. BOOL isVerticalForm = NO;
  313. BOOL rowMaySeparated = NO;
  314. NSMutableDictionary *frameAttrs = nil;
  315. CTFramesetterRef ctSetter = NULL;
  316. CTFrameRef ctFrame = NULL;
  317. CFArrayRef ctLines = nil;
  318. CGPoint *lineOrigins = NULL;
  319. NSUInteger lineCount = 0;
  320. NSMutableArray *lines = nil;
  321. NSMutableArray *attachments = nil;
  322. NSMutableArray *attachmentRanges = nil;
  323. NSMutableArray *attachmentRects = nil;
  324. NSMutableSet *attachmentContentsSet = nil;
  325. BOOL needTruncation = NO;
  326. NSAttributedString *truncationToken = nil;
  327. YYTextLine *truncatedLine = nil;
  328. YYRowEdge *lineRowsEdge = NULL;
  329. NSUInteger *lineRowsIndex = NULL;
  330. NSRange visibleRange;
  331. NSUInteger maximumNumberOfRows = 0;
  332. BOOL constraintSizeIsExtended = NO;
  333. CGRect constraintRectBeforeExtended = {0};
  334. text = text.mutableCopy;
  335. container = container.copy;
  336. if (!text || !container) return nil;
  337. if (range.location + range.length > text.length) return nil;
  338. container->_readonly = YES;
  339. maximumNumberOfRows = container.maximumNumberOfRows;
  340. // CoreText bug when draw joined emoji since iOS 8.3.
  341. // See -[NSMutableAttributedString setClearColorToJoinedEmoji] for more information.
  342. static BOOL needFixJoinedEmojiBug = NO;
  343. // It may use larger constraint size when create CTFrame with
  344. // CTFramesetterCreateFrame in iOS 10.
  345. static BOOL needFixLayoutSizeBug = NO;
  346. static dispatch_once_t onceToken;
  347. dispatch_once(&onceToken, ^{
  348. CGFloat systemVersionFloat = [UIDevice currentDevice].systemVersion.floatValue;
  349. if (8.3 <= systemVersionFloat && systemVersionFloat < 9) {
  350. needFixJoinedEmojiBug = YES;
  351. }
  352. if (systemVersionFloat >= 10) {
  353. needFixLayoutSizeBug = YES;
  354. }
  355. });
  356. if (needFixJoinedEmojiBug) {
  357. [((NSMutableAttributedString *)text) setClearColorToJoinedEmoji];
  358. }
  359. layout = [[YYTextLayout alloc] _init];
  360. layout.text = text;
  361. layout.container = container;
  362. layout.range = range;
  363. isVerticalForm = container.verticalForm;
  364. // set cgPath and cgPathBox
  365. if (container.path == nil && container.exclusionPaths.count == 0) {
  366. if (container.size.width <= 0 || container.size.height <= 0) goto fail;
  367. CGRect rect = (CGRect) {CGPointZero, container.size };
  368. if (needFixLayoutSizeBug) {
  369. constraintSizeIsExtended = YES;
  370. constraintRectBeforeExtended = UIEdgeInsetsInsetRect(rect, container.insets);
  371. constraintRectBeforeExtended = CGRectStandardize(constraintRectBeforeExtended);
  372. if (container.isVerticalForm) {
  373. rect.size.width = YYTextContainerMaxSize.width;
  374. } else {
  375. rect.size.height = YYTextContainerMaxSize.height;
  376. }
  377. }
  378. rect = UIEdgeInsetsInsetRect(rect, container.insets);
  379. rect = CGRectStandardize(rect);
  380. cgPathBox = rect;
  381. rect = CGRectApplyAffineTransform(rect, CGAffineTransformMakeScale(1, -1));
  382. cgPath = CGPathCreateWithRect(rect, NULL); // let CGPathIsRect() returns true
  383. } else if (container.path && CGPathIsRect(container.path.CGPath, &cgPathBox) && container.exclusionPaths.count == 0) {
  384. CGRect rect = CGRectApplyAffineTransform(cgPathBox, CGAffineTransformMakeScale(1, -1));
  385. cgPath = CGPathCreateWithRect(rect, NULL); // let CGPathIsRect() returns true
  386. } else {
  387. rowMaySeparated = YES;
  388. CGMutablePathRef path = NULL;
  389. if (container.path) {
  390. path = CGPathCreateMutableCopy(container.path.CGPath);
  391. } else {
  392. CGRect rect = (CGRect) {CGPointZero, container.size };
  393. rect = UIEdgeInsetsInsetRect(rect, container.insets);
  394. CGPathRef rectPath = CGPathCreateWithRect(rect, NULL);
  395. if (rectPath) {
  396. path = CGPathCreateMutableCopy(rectPath);
  397. CGPathRelease(rectPath);
  398. }
  399. }
  400. if (path) {
  401. [layout.container.exclusionPaths enumerateObjectsUsingBlock: ^(UIBezierPath *onePath, NSUInteger idx, BOOL *stop) {
  402. CGPathAddPath(path, NULL, onePath.CGPath);
  403. }];
  404. cgPathBox = CGPathGetPathBoundingBox(path);
  405. CGAffineTransform trans = CGAffineTransformMakeScale(1, -1);
  406. CGMutablePathRef transPath = CGPathCreateMutableCopyByTransformingPath(path, &trans);
  407. CGPathRelease(path);
  408. path = transPath;
  409. }
  410. cgPath = path;
  411. }
  412. if (!cgPath) goto fail;
  413. // frame setter config
  414. frameAttrs = [NSMutableDictionary dictionary];
  415. if (container.isPathFillEvenOdd == NO) {
  416. frameAttrs[(id)kCTFramePathFillRuleAttributeName] = @(kCTFramePathFillWindingNumber);
  417. }
  418. if (container.pathLineWidth > 0) {
  419. frameAttrs[(id)kCTFramePathWidthAttributeName] = @(container.pathLineWidth);
  420. }
  421. if (container.isVerticalForm == YES) {
  422. frameAttrs[(id)kCTFrameProgressionAttributeName] = @(kCTFrameProgressionRightToLeft);
  423. }
  424. // create CoreText objects
  425. ctSetter = CTFramesetterCreateWithAttributedString((CFTypeRef)text);
  426. if (!ctSetter) goto fail;
  427. ctFrame = CTFramesetterCreateFrame(ctSetter, YYCFRangeFromNSRange(range), cgPath, (CFTypeRef)frameAttrs);
  428. if (!ctFrame) goto fail;
  429. lines = [NSMutableArray new];
  430. ctLines = CTFrameGetLines(ctFrame);
  431. lineCount = CFArrayGetCount(ctLines);
  432. if (lineCount > 0) {
  433. lineOrigins = malloc(lineCount * sizeof(CGPoint));
  434. if (lineOrigins == NULL) goto fail;
  435. CTFrameGetLineOrigins(ctFrame, CFRangeMake(0, lineCount), lineOrigins);
  436. }
  437. CGRect textBoundingRect = CGRectZero;
  438. CGSize textBoundingSize = CGSizeZero;
  439. NSInteger rowIdx = -1;
  440. NSUInteger rowCount = 0;
  441. CGRect lastRect = CGRectMake(0, -FLT_MAX, 0, 0);
  442. CGPoint lastPosition = CGPointMake(0, -FLT_MAX);
  443. if (isVerticalForm) {
  444. lastRect = CGRectMake(FLT_MAX, 0, 0, 0);
  445. lastPosition = CGPointMake(FLT_MAX, 0);
  446. }
  447. // calculate line frame
  448. NSUInteger lineCurrentIdx = 0;
  449. for (NSUInteger i = 0; i < lineCount; i++) {
  450. CTLineRef ctLine = CFArrayGetValueAtIndex(ctLines, i);
  451. CFArrayRef ctRuns = CTLineGetGlyphRuns(ctLine);
  452. if (!ctRuns || CFArrayGetCount(ctRuns) == 0) continue;
  453. // CoreText coordinate system
  454. CGPoint ctLineOrigin = lineOrigins[i];
  455. // UIKit coordinate system
  456. CGPoint position;
  457. position.x = cgPathBox.origin.x + ctLineOrigin.x;
  458. position.y = cgPathBox.size.height + cgPathBox.origin.y - ctLineOrigin.y;
  459. YYTextLine *line = [YYTextLine lineWithCTLine:ctLine position:position vertical:isVerticalForm];
  460. CGRect rect = line.bounds;
  461. if (constraintSizeIsExtended) {
  462. if (isVerticalForm) {
  463. if (rect.origin.x + rect.size.width >
  464. constraintRectBeforeExtended.origin.x +
  465. constraintRectBeforeExtended.size.width) break;
  466. } else {
  467. if (rect.origin.y + rect.size.height >
  468. constraintRectBeforeExtended.origin.y +
  469. constraintRectBeforeExtended.size.height) break;
  470. }
  471. }
  472. BOOL newRow = YES;
  473. if (rowMaySeparated && position.x != lastPosition.x) {
  474. if (isVerticalForm) {
  475. if (rect.size.width > lastRect.size.width) {
  476. if (rect.origin.x > lastPosition.x && lastPosition.x > rect.origin.x - rect.size.width) newRow = NO;
  477. } else {
  478. if (lastRect.origin.x > position.x && position.x > lastRect.origin.x - lastRect.size.width) newRow = NO;
  479. }
  480. } else {
  481. if (rect.size.height > lastRect.size.height) {
  482. if (rect.origin.y < lastPosition.y && lastPosition.y < rect.origin.y + rect.size.height) newRow = NO;
  483. } else {
  484. if (lastRect.origin.y < position.y && position.y < lastRect.origin.y + lastRect.size.height) newRow = NO;
  485. }
  486. }
  487. }
  488. if (newRow) rowIdx++;
  489. lastRect = rect;
  490. lastPosition = position;
  491. line.index = lineCurrentIdx;
  492. line.row = rowIdx;
  493. [lines addObject:line];
  494. rowCount = rowIdx + 1;
  495. lineCurrentIdx ++;
  496. if (i == 0) textBoundingRect = rect;
  497. else {
  498. if (maximumNumberOfRows == 0 || rowIdx < maximumNumberOfRows) {
  499. textBoundingRect = CGRectUnion(textBoundingRect, rect);
  500. }
  501. }
  502. }
  503. if (rowCount > 0) {
  504. if (maximumNumberOfRows > 0) {
  505. if (rowCount > maximumNumberOfRows) {
  506. needTruncation = YES;
  507. rowCount = maximumNumberOfRows;
  508. do {
  509. YYTextLine *line = lines.lastObject;
  510. if (!line) break;
  511. if (line.row < rowCount) break;
  512. [lines removeLastObject];
  513. } while (1);
  514. }
  515. }
  516. YYTextLine *lastLine = lines.lastObject;
  517. if (!needTruncation && lastLine.range.location + lastLine.range.length < text.length) {
  518. needTruncation = YES;
  519. }
  520. // Give user a chance to modify the line's position.
  521. if (container.linePositionModifier) {
  522. [container.linePositionModifier modifyLines:lines fromText:text inContainer:container];
  523. textBoundingRect = CGRectZero;
  524. for (NSUInteger i = 0, max = lines.count; i < max; i++) {
  525. YYTextLine *line = lines[i];
  526. if (i == 0) textBoundingRect = line.bounds;
  527. else textBoundingRect = CGRectUnion(textBoundingRect, line.bounds);
  528. }
  529. }
  530. lineRowsEdge = calloc(rowCount, sizeof(YYRowEdge));
  531. if (lineRowsEdge == NULL) goto fail;
  532. lineRowsIndex = calloc(rowCount, sizeof(NSUInteger));
  533. if (lineRowsIndex == NULL) goto fail;
  534. NSInteger lastRowIdx = -1;
  535. CGFloat lastHead = 0;
  536. CGFloat lastFoot = 0;
  537. for (NSUInteger i = 0, max = lines.count; i < max; i++) {
  538. YYTextLine *line = lines[i];
  539. CGRect rect = line.bounds;
  540. if ((NSInteger)line.row != lastRowIdx) {
  541. if (lastRowIdx >= 0) {
  542. lineRowsEdge[lastRowIdx] = (YYRowEdge) {.head = lastHead, .foot = lastFoot };
  543. }
  544. lastRowIdx = line.row;
  545. lineRowsIndex[lastRowIdx] = i;
  546. if (isVerticalForm) {
  547. lastHead = rect.origin.x + rect.size.width;
  548. lastFoot = lastHead - rect.size.width;
  549. } else {
  550. lastHead = rect.origin.y;
  551. lastFoot = lastHead + rect.size.height;
  552. }
  553. } else {
  554. if (isVerticalForm) {
  555. lastHead = MAX(lastHead, rect.origin.x + rect.size.width);
  556. lastFoot = MIN(lastFoot, rect.origin.x);
  557. } else {
  558. lastHead = MIN(lastHead, rect.origin.y);
  559. lastFoot = MAX(lastFoot, rect.origin.y + rect.size.height);
  560. }
  561. }
  562. }
  563. lineRowsEdge[lastRowIdx] = (YYRowEdge) {.head = lastHead, .foot = lastFoot };
  564. for (NSUInteger i = 1; i < rowCount; i++) {
  565. YYRowEdge v0 = lineRowsEdge[i - 1];
  566. YYRowEdge v1 = lineRowsEdge[i];
  567. lineRowsEdge[i - 1].foot = lineRowsEdge[i].head = (v0.foot + v1.head) * 0.5;
  568. }
  569. }
  570. { // calculate bounding size
  571. CGRect rect = textBoundingRect;
  572. if (container.path) {
  573. if (container.pathLineWidth > 0) {
  574. CGFloat inset = container.pathLineWidth / 2;
  575. rect = CGRectInset(rect, -inset, -inset);
  576. }
  577. } else {
  578. rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetsInvert(container.insets));
  579. }
  580. rect = CGRectStandardize(rect);
  581. CGSize size = rect.size;
  582. if (container.verticalForm) {
  583. size.width += container.size.width - (rect.origin.x + rect.size.width);
  584. } else {
  585. size.width += rect.origin.x;
  586. }
  587. size.height += rect.origin.y;
  588. if (size.width < 0) size.width = 0;
  589. if (size.height < 0) size.height = 0;
  590. size.width = ceil(size.width);
  591. size.height = ceil(size.height);
  592. textBoundingSize = size;
  593. }
  594. visibleRange = YYNSRangeFromCFRange(CTFrameGetVisibleStringRange(ctFrame));
  595. if (needTruncation) {
  596. YYTextLine *lastLine = lines.lastObject;
  597. NSRange lastRange = lastLine.range;
  598. visibleRange.length = lastRange.location + lastRange.length - visibleRange.location;
  599. // create truncated line
  600. if (container.truncationType != YYTextTruncationTypeNone) {
  601. CTLineRef truncationTokenLine = NULL;
  602. if (container.truncationToken) {
  603. truncationToken = container.truncationToken;
  604. truncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef)truncationToken);
  605. } else {
  606. CFArrayRef runs = CTLineGetGlyphRuns(lastLine.CTLine);
  607. NSUInteger runCount = CFArrayGetCount(runs);
  608. NSMutableDictionary *attrs = nil;
  609. if (runCount > 0) {
  610. CTRunRef run = CFArrayGetValueAtIndex(runs, runCount - 1);
  611. attrs = (id)CTRunGetAttributes(run);
  612. attrs = attrs ? attrs.mutableCopy : [NSMutableArray new];
  613. [attrs removeObjectsForKeys:[NSMutableAttributedString allDiscontinuousAttributeKeys]];
  614. CTFontRef font = (__bridge CFTypeRef)attrs[(id)kCTFontAttributeName];
  615. CGFloat fontSize = font ? CTFontGetSize(font) : 12.0;
  616. UIFont *uiFont = [UIFont systemFontOfSize:fontSize * 0.9];
  617. font = [uiFont CTFontRef];
  618. if (font) {
  619. attrs[(id)kCTFontAttributeName] = (__bridge id)(font);
  620. uiFont = nil;
  621. CFRelease(font);
  622. }
  623. CGColorRef color = (__bridge CGColorRef)(attrs[(id)kCTForegroundColorAttributeName]);
  624. if (color && CFGetTypeID(color) == CGColorGetTypeID() && CGColorGetAlpha(color) == 0) {
  625. // ignore clear color
  626. [attrs removeObjectForKey:(id)kCTForegroundColorAttributeName];
  627. }
  628. if (!attrs) attrs = [NSMutableDictionary new];
  629. }
  630. truncationToken = [[NSAttributedString alloc] initWithString:YYTextTruncationToken attributes:attrs];
  631. truncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef)truncationToken);
  632. }
  633. if (truncationTokenLine) {
  634. CTLineTruncationType type = kCTLineTruncationEnd;
  635. if (container.truncationType == YYTextTruncationTypeStart) {
  636. type = kCTLineTruncationStart;
  637. } else if (container.truncationType == YYTextTruncationTypeMiddle) {
  638. type = kCTLineTruncationMiddle;
  639. }
  640. NSMutableAttributedString *lastLineText = [text attributedSubstringFromRange:lastLine.range].mutableCopy;
  641. [lastLineText appendAttributedString:truncationToken];
  642. CTLineRef ctLastLineExtend = CTLineCreateWithAttributedString((CFAttributedStringRef)lastLineText);
  643. if (ctLastLineExtend) {
  644. CGFloat truncatedWidth = lastLine.width;
  645. CGRect cgPathRect = CGRectZero;
  646. if (CGPathIsRect(cgPath, &cgPathRect)) {
  647. if (isVerticalForm) {
  648. truncatedWidth = cgPathRect.size.height;
  649. } else {
  650. truncatedWidth = cgPathRect.size.width;
  651. }
  652. }
  653. CTLineRef ctTruncatedLine = CTLineCreateTruncatedLine(ctLastLineExtend, truncatedWidth, type, truncationTokenLine);
  654. CFRelease(ctLastLineExtend);
  655. if (ctTruncatedLine) {
  656. truncatedLine = [YYTextLine lineWithCTLine:ctTruncatedLine position:lastLine.position vertical:isVerticalForm];
  657. truncatedLine.index = lastLine.index;
  658. truncatedLine.row = lastLine.row;
  659. CFRelease(ctTruncatedLine);
  660. }
  661. }
  662. CFRelease(truncationTokenLine);
  663. }
  664. }
  665. }
  666. if (isVerticalForm) {
  667. NSCharacterSet *rotateCharset = YYTextVerticalFormRotateCharacterSet();
  668. NSCharacterSet *rotateMoveCharset = YYTextVerticalFormRotateAndMoveCharacterSet();
  669. void (^lineBlock)(YYTextLine *) = ^(YYTextLine *line){
  670. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  671. if (!runs) return;
  672. NSUInteger runCount = CFArrayGetCount(runs);
  673. if (runCount == 0) return;
  674. NSMutableArray *lineRunRanges = [NSMutableArray new];
  675. line.verticalRotateRange = lineRunRanges;
  676. for (NSUInteger r = 0; r < runCount; r++) {
  677. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  678. NSMutableArray *runRanges = [NSMutableArray new];
  679. [lineRunRanges addObject:runRanges];
  680. NSUInteger glyphCount = CTRunGetGlyphCount(run);
  681. if (glyphCount == 0) continue;
  682. CFIndex runStrIdx[glyphCount + 1];
  683. CTRunGetStringIndices(run, CFRangeMake(0, 0), runStrIdx);
  684. CFRange runStrRange = CTRunGetStringRange(run);
  685. runStrIdx[glyphCount] = runStrRange.location + runStrRange.length;
  686. CFDictionaryRef runAttrs = CTRunGetAttributes(run);
  687. CTFontRef font = CFDictionaryGetValue(runAttrs, kCTFontAttributeName);
  688. BOOL isColorGlyph = CTFontContainsColorBitmapGlyphs(font);
  689. NSUInteger prevIdx = 0;
  690. YYTextRunGlyphDrawMode prevMode = YYTextRunGlyphDrawModeHorizontal;
  691. NSString *layoutStr = layout.text.string;
  692. for (NSUInteger g = 0; g < glyphCount; g++) {
  693. BOOL glyphRotate = 0, glyphRotateMove = NO;
  694. CFIndex runStrLen = runStrIdx[g + 1] - runStrIdx[g];
  695. if (isColorGlyph) {
  696. glyphRotate = YES;
  697. } else if (runStrLen == 1) {
  698. unichar c = [layoutStr characterAtIndex:runStrIdx[g]];
  699. glyphRotate = [rotateCharset characterIsMember:c];
  700. if (glyphRotate) glyphRotateMove = [rotateMoveCharset characterIsMember:c];
  701. } else if (runStrLen > 1){
  702. NSString *glyphStr = [layoutStr substringWithRange:NSMakeRange(runStrIdx[g], runStrLen)];
  703. BOOL glyphRotate = [glyphStr rangeOfCharacterFromSet:rotateCharset].location != NSNotFound;
  704. if (glyphRotate) glyphRotateMove = [glyphStr rangeOfCharacterFromSet:rotateMoveCharset].location != NSNotFound;
  705. }
  706. YYTextRunGlyphDrawMode mode = glyphRotateMove ? YYTextRunGlyphDrawModeVerticalRotateMove : (glyphRotate ? YYTextRunGlyphDrawModeVerticalRotate : YYTextRunGlyphDrawModeHorizontal);
  707. if (g == 0) {
  708. prevMode = mode;
  709. } else if (mode != prevMode) {
  710. YYTextRunGlyphRange *aRange = [YYTextRunGlyphRange rangeWithRange:NSMakeRange(prevIdx, g - prevIdx) drawMode:prevMode];
  711. [runRanges addObject:aRange];
  712. prevIdx = g;
  713. prevMode = mode;
  714. }
  715. }
  716. if (prevIdx < glyphCount) {
  717. YYTextRunGlyphRange *aRange = [YYTextRunGlyphRange rangeWithRange:NSMakeRange(prevIdx, glyphCount - prevIdx) drawMode:prevMode];
  718. [runRanges addObject:aRange];
  719. }
  720. }
  721. };
  722. for (YYTextLine *line in lines) {
  723. lineBlock(line);
  724. }
  725. if (truncatedLine) lineBlock(truncatedLine);
  726. }
  727. if (visibleRange.length > 0) {
  728. layout.needDrawText = YES;
  729. void (^block)(NSDictionary *attrs, NSRange range, BOOL *stop) = ^(NSDictionary *attrs, NSRange range, BOOL *stop) {
  730. if (attrs[YYTextHighlightAttributeName]) layout.containsHighlight = YES;
  731. if (attrs[YYTextBlockBorderAttributeName]) layout.needDrawBlockBorder = YES;
  732. if (attrs[YYTextBackgroundBorderAttributeName]) layout.needDrawBackgroundBorder = YES;
  733. if (attrs[YYTextShadowAttributeName] || attrs[NSShadowAttributeName]) layout.needDrawShadow = YES;
  734. if (attrs[YYTextUnderlineAttributeName]) layout.needDrawUnderline = YES;
  735. if (attrs[YYTextAttachmentAttributeName]) layout.needDrawAttachment = YES;
  736. if (attrs[YYTextInnerShadowAttributeName]) layout.needDrawInnerShadow = YES;
  737. if (attrs[YYTextStrikethroughAttributeName]) layout.needDrawStrikethrough = YES;
  738. if (attrs[YYTextBorderAttributeName]) layout.needDrawBorder = YES;
  739. };
  740. [layout.text enumerateAttributesInRange:visibleRange options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:block];
  741. if (truncatedLine) {
  742. [truncationToken enumerateAttributesInRange:NSMakeRange(0, truncationToken.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:block];
  743. }
  744. }
  745. attachments = [NSMutableArray new];
  746. attachmentRanges = [NSMutableArray new];
  747. attachmentRects = [NSMutableArray new];
  748. attachmentContentsSet = [NSMutableSet new];
  749. for (NSUInteger i = 0, max = lines.count; i < max; i++) {
  750. YYTextLine *line = lines[i];
  751. if (truncatedLine && line.index == truncatedLine.index) line = truncatedLine;
  752. if (line.attachments.count > 0) {
  753. [attachments addObjectsFromArray:line.attachments];
  754. [attachmentRanges addObjectsFromArray:line.attachmentRanges];
  755. [attachmentRects addObjectsFromArray:line.attachmentRects];
  756. for (YYTextAttachment *attachment in line.attachments) {
  757. if (attachment.content) {
  758. [attachmentContentsSet addObject:attachment.content];
  759. }
  760. }
  761. }
  762. }
  763. if (attachments.count == 0) {
  764. attachments = attachmentRanges = attachmentRects = nil;
  765. }
  766. layout.frameSetter = ctSetter;
  767. layout.frame = ctFrame;
  768. layout.lines = lines;
  769. layout.truncatedLine = truncatedLine;
  770. layout.attachments = attachments;
  771. layout.attachmentRanges = attachmentRanges;
  772. layout.attachmentRects = attachmentRects;
  773. layout.attachmentContentsSet = attachmentContentsSet;
  774. layout.rowCount = rowCount;
  775. layout.visibleRange = visibleRange;
  776. layout.textBoundingRect = textBoundingRect;
  777. layout.textBoundingSize = textBoundingSize;
  778. layout.lineRowsEdge = lineRowsEdge;
  779. layout.lineRowsIndex = lineRowsIndex;
  780. CFRelease(cgPath);
  781. CFRelease(ctSetter);
  782. CFRelease(ctFrame);
  783. if (lineOrigins) free(lineOrigins);
  784. return layout;
  785. fail:
  786. if (cgPath) CFRelease(cgPath);
  787. if (ctSetter) CFRelease(ctSetter);
  788. if (ctFrame) CFRelease(ctFrame);
  789. if (lineOrigins) free(lineOrigins);
  790. if (lineRowsEdge) free(lineRowsEdge);
  791. if (lineRowsIndex) free(lineRowsIndex);
  792. return nil;
  793. }
  794. + (NSArray *)layoutWithContainers:(NSArray *)containers text:(NSAttributedString *)text {
  795. return [self layoutWithContainers:containers text:text range:NSMakeRange(0, text.length)];
  796. }
  797. + (NSArray *)layoutWithContainers:(NSArray *)containers text:(NSAttributedString *)text range:(NSRange)range {
  798. if (!containers || !text) return nil;
  799. if (range.location + range.length > text.length) return nil;
  800. NSMutableArray *layouts = [NSMutableArray array];
  801. for (NSUInteger i = 0, max = containers.count; i < max; i++) {
  802. YYTextContainer *container = containers[i];
  803. YYTextLayout *layout = [self layoutWithContainer:container text:text range:range];
  804. if (!layout) return nil;
  805. NSInteger length = (NSInteger)range.length - (NSInteger)layout.visibleRange.length;
  806. if (length <= 0) {
  807. range.length = 0;
  808. range.location = text.length;
  809. } else {
  810. range.length = length;
  811. range.location += layout.visibleRange.length;
  812. }
  813. }
  814. return layouts;
  815. }
  816. - (void)setFrameSetter:(CTFramesetterRef)frameSetter {
  817. if (_frameSetter != frameSetter) {
  818. if (frameSetter) CFRetain(frameSetter);
  819. if (_frameSetter) CFRelease(_frameSetter);
  820. _frameSetter = frameSetter;
  821. }
  822. }
  823. - (void)setFrame:(CTFrameRef)frame {
  824. if (_frame != frame) {
  825. if (frame) CFRetain(frame);
  826. if (_frame) CFRelease(_frame);
  827. _frame = frame;
  828. }
  829. }
  830. - (void)dealloc {
  831. if (_frameSetter) CFRelease(_frameSetter);
  832. if (_frame) CFRelease(_frame);
  833. if (_lineRowsIndex) free(_lineRowsIndex);
  834. if (_lineRowsEdge) free(_lineRowsEdge);
  835. }
  836. #pragma mark - Coding
  837. - (void)encodeWithCoder:(NSCoder *)aCoder {
  838. NSData *textData = [YYTextArchiver archivedDataWithRootObject:_text];
  839. [aCoder encodeObject:textData forKey:@"text"];
  840. [aCoder encodeObject:_container forKey:@"container"];
  841. [aCoder encodeObject:[NSValue valueWithRange:_range] forKey:@"range"];
  842. }
  843. - (id)initWithCoder:(NSCoder *)aDecoder {
  844. NSData *textData = [aDecoder decodeObjectForKey:@"text"];
  845. NSAttributedString *text = [YYTextUnarchiver unarchiveObjectWithData:textData];
  846. YYTextContainer *container = [aDecoder decodeObjectForKey:@"container"];
  847. NSRange range = ((NSValue *)[aDecoder decodeObjectForKey:@"range"]).rangeValue;
  848. self = [self.class layoutWithContainer:container text:text range:range];
  849. return self;
  850. }
  851. #pragma mark - Copying
  852. - (id)copyWithZone:(NSZone *)zone {
  853. return self; // readonly object
  854. }
  855. #pragma mark - Query
  856. /**
  857. Get the row index with 'edge' distance.
  858. @param edge The distance from edge to the point.
  859. If vertical form, the edge is left edge, otherwise the edge is top edge.
  860. @return Returns NSNotFound if there's no row at the point.
  861. */
  862. - (NSUInteger)_rowIndexForEdge:(CGFloat)edge {
  863. if (_rowCount == 0) return NSNotFound;
  864. BOOL isVertical = _container.verticalForm;
  865. NSUInteger lo = 0, hi = _rowCount - 1, mid = 0;
  866. NSUInteger rowIdx = NSNotFound;
  867. while (lo <= hi) {
  868. mid = (lo + hi) / 2;
  869. YYRowEdge oneEdge = _lineRowsEdge[mid];
  870. if (isVertical ?
  871. (oneEdge.foot <= edge && edge <= oneEdge.head) :
  872. (oneEdge.head <= edge && edge <= oneEdge.foot)) {
  873. rowIdx = mid;
  874. break;
  875. }
  876. if ((isVertical ? (edge > oneEdge.head) : (edge < oneEdge.head))) {
  877. if (mid == 0) break;
  878. hi = mid - 1;
  879. } else {
  880. lo = mid + 1;
  881. }
  882. }
  883. return rowIdx;
  884. }
  885. /**
  886. Get the closest row index with 'edge' distance.
  887. @param edge The distance from edge to the point.
  888. If vertical form, the edge is left edge, otherwise the edge is top edge.
  889. @return Returns NSNotFound if there's no line.
  890. */
  891. - (NSUInteger)_closestRowIndexForEdge:(CGFloat)edge {
  892. if (_rowCount == 0) return NSNotFound;
  893. NSUInteger rowIdx = [self _rowIndexForEdge:edge];
  894. if (rowIdx == NSNotFound) {
  895. if (_container.verticalForm) {
  896. if (edge > _lineRowsEdge[0].head) {
  897. rowIdx = 0;
  898. } else if (edge < _lineRowsEdge[_rowCount - 1].foot) {
  899. rowIdx = _rowCount - 1;
  900. }
  901. } else {
  902. if (edge < _lineRowsEdge[0].head) {
  903. rowIdx = 0;
  904. } else if (edge > _lineRowsEdge[_rowCount - 1].foot) {
  905. rowIdx = _rowCount - 1;
  906. }
  907. }
  908. }
  909. return rowIdx;
  910. }
  911. /**
  912. Get a CTRun from a line position.
  913. @param line The text line.
  914. @param position The position in the whole text.
  915. @return Returns NULL if not found (no CTRun at the position).
  916. */
  917. - (CTRunRef)_runForLine:(YYTextLine *)line position:(YYTextPosition *)position {
  918. if (!line || !position) return NULL;
  919. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  920. for (NSUInteger i = 0, max = CFArrayGetCount(runs); i < max; i++) {
  921. CTRunRef run = CFArrayGetValueAtIndex(runs, i);
  922. CFRange range = CTRunGetStringRange(run);
  923. if (position.affinity == YYTextAffinityBackward) {
  924. if (range.location < position.offset && position.offset <= range.location + range.length) {
  925. return run;
  926. }
  927. } else {
  928. if (range.location <= position.offset && position.offset < range.location + range.length) {
  929. return run;
  930. }
  931. }
  932. }
  933. return NULL;
  934. }
  935. /**
  936. Whether the position is inside a composed character sequence.
  937. @param line The text line.
  938. @param position Text text position in whole text.
  939. @param block The block to be executed before returns YES.
  940. left: left X offset
  941. right: right X offset
  942. prev: left position
  943. next: right position
  944. */
  945. - (BOOL)_insideComposedCharacterSequences:(YYTextLine *)line position:(NSUInteger)position block:(void (^)(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next))block {
  946. NSRange range = line.range;
  947. if (range.length == 0) return NO;
  948. __block BOOL inside = NO;
  949. __block NSUInteger _prev, _next;
  950. [_text.string enumerateSubstringsInRange:range options:NSStringEnumerationByComposedCharacterSequences usingBlock: ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  951. NSUInteger prev = substringRange.location;
  952. NSUInteger next = substringRange.location + substringRange.length;
  953. if (prev == position || next == position) {
  954. *stop = YES;
  955. }
  956. if (prev < position && position < next) {
  957. inside = YES;
  958. _prev = prev;
  959. _next = next;
  960. *stop = YES;
  961. }
  962. }];
  963. if (inside && block) {
  964. CGFloat left = [self offsetForTextPosition:_prev lineIndex:line.index];
  965. CGFloat right = [self offsetForTextPosition:_next lineIndex:line.index];
  966. block(left, right, _prev, _next);
  967. }
  968. return inside;
  969. }
  970. /**
  971. Whether the position is inside an emoji (such as National Flag Emoji).
  972. @param line The text line.
  973. @param position Text text position in whole text.
  974. @param block Yhe block to be executed before returns YES.
  975. left: emoji's left X offset
  976. right: emoji's right X offset
  977. prev: emoji's left position
  978. next: emoji's right position
  979. */
  980. - (BOOL)_insideEmoji:(YYTextLine *)line position:(NSUInteger)position block:(void (^)(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next))block {
  981. if (!line) return NO;
  982. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  983. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  984. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  985. NSUInteger glyphCount = CTRunGetGlyphCount(run);
  986. if (glyphCount == 0) continue;
  987. CFRange range = CTRunGetStringRange(run);
  988. if (range.length <= 1) continue;
  989. if (position <= range.location || position >= range.location + range.length) continue;
  990. CFDictionaryRef attrs = CTRunGetAttributes(run);
  991. CTFontRef font = CFDictionaryGetValue(attrs, kCTFontAttributeName);
  992. if (!CTFontContainsColorBitmapGlyphs(font)) continue;
  993. // Here's Emoji runs (larger than 1 unichar), and position is inside the range.
  994. CFIndex indices[glyphCount];
  995. CTRunGetStringIndices(run, CFRangeMake(0, glyphCount), indices);
  996. for (NSUInteger g = 0; g < glyphCount; g++) {
  997. CFIndex prev = indices[g];
  998. CFIndex next = g + 1 < glyphCount ? indices[g + 1] : range.location + range.length;
  999. if (position == prev) break; // Emoji edge
  1000. if (prev < position && position < next) { // inside an emoji (such as National Flag Emoji)
  1001. CGPoint pos = CGPointZero;
  1002. CGSize adv = CGSizeZero;
  1003. CTRunGetPositions(run, CFRangeMake(g, 1), &pos);
  1004. CTRunGetAdvances(run, CFRangeMake(g, 1), &adv);
  1005. if (block) {
  1006. block(line.position.x + pos.x,
  1007. line.position.x + pos.x + adv.width,
  1008. prev, next);
  1009. }
  1010. return YES;
  1011. }
  1012. }
  1013. }
  1014. return NO;
  1015. }
  1016. /**
  1017. Whether the write direction is RTL at the specified point
  1018. @param line The text line
  1019. @param point The point in layout.
  1020. @return YES if RTL.
  1021. */
  1022. - (BOOL)_isRightToLeftInLine:(YYTextLine *)line atPoint:(CGPoint)point {
  1023. if (!line) return NO;
  1024. // get write direction
  1025. BOOL RTL = NO;
  1026. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  1027. for (NSUInteger r = 0, max = CFArrayGetCount(runs); r < max; r++) {
  1028. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  1029. CGPoint glyphPosition;
  1030. CTRunGetPositions(run, CFRangeMake(0, 1), &glyphPosition);
  1031. if (_container.verticalForm) {
  1032. CGFloat runX = glyphPosition.x;
  1033. runX += line.position.y;
  1034. CGFloat runWidth = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
  1035. if (runX <= point.y && point.y <= runX + runWidth) {
  1036. if (CTRunGetStatus(run) & kCTRunStatusRightToLeft) RTL = YES;
  1037. break;
  1038. }
  1039. } else {
  1040. CGFloat runX = glyphPosition.x;
  1041. runX += line.position.x;
  1042. CGFloat runWidth = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
  1043. if (runX <= point.x && point.x <= runX + runWidth) {
  1044. if (CTRunGetStatus(run) & kCTRunStatusRightToLeft) RTL = YES;
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. return RTL;
  1050. }
  1051. /**
  1052. Correct the range's edge.
  1053. */
  1054. - (YYTextRange *)_correctedRangeWithEdge:(YYTextRange *)range {
  1055. NSRange visibleRange = self.visibleRange;
  1056. YYTextPosition *start = range.start;
  1057. YYTextPosition *end = range.end;
  1058. if (start.offset == visibleRange.location && start.affinity == YYTextAffinityBackward) {
  1059. start = [YYTextPosition positionWithOffset:start.offset affinity:YYTextAffinityForward];
  1060. }
  1061. if (end.offset == visibleRange.location + visibleRange.length && start.affinity == YYTextAffinityForward) {
  1062. end = [YYTextPosition positionWithOffset:end.offset affinity:YYTextAffinityBackward];
  1063. }
  1064. if (start != range.start || end != range.end) {
  1065. range = [YYTextRange rangeWithStart:start end:end];
  1066. }
  1067. return range;
  1068. }
  1069. - (NSUInteger)lineIndexForRow:(NSUInteger)row {
  1070. if (row >= _rowCount) return NSNotFound;
  1071. return _lineRowsIndex[row];
  1072. }
  1073. - (NSUInteger)lineCountForRow:(NSUInteger)row {
  1074. if (row >= _rowCount) return NSNotFound;
  1075. if (row == _rowCount - 1) {
  1076. return _lines.count - _lineRowsIndex[row];
  1077. } else {
  1078. return _lineRowsIndex[row + 1] - _lineRowsIndex[row];
  1079. }
  1080. }
  1081. - (NSUInteger)rowIndexForLine:(NSUInteger)line {
  1082. if (line >= _lines.count) return NSNotFound;
  1083. return ((YYTextLine *)_lines[line]).row;
  1084. }
  1085. - (NSUInteger)lineIndexForPoint:(CGPoint)point {
  1086. if (_lines.count == 0 || _rowCount == 0) return NSNotFound;
  1087. NSUInteger rowIdx = [self _rowIndexForEdge:_container.verticalForm ? point.x : point.y];
  1088. if (rowIdx == NSNotFound) return NSNotFound;
  1089. NSUInteger lineIdx0 = _lineRowsIndex[rowIdx];
  1090. NSUInteger lineIdx1 = rowIdx == _rowCount - 1 ? _lines.count - 1 : _lineRowsIndex[rowIdx + 1] - 1;
  1091. for (NSUInteger i = lineIdx0; i <= lineIdx1; i++) {
  1092. CGRect bounds = ((YYTextLine *)_lines[i]).bounds;
  1093. if (CGRectContainsPoint(bounds, point)) return i;
  1094. }
  1095. return NSNotFound;
  1096. }
  1097. - (NSUInteger)closestLineIndexForPoint:(CGPoint)point {
  1098. BOOL isVertical = _container.verticalForm;
  1099. if (_lines.count == 0 || _rowCount == 0) return NSNotFound;
  1100. NSUInteger rowIdx = [self _closestRowIndexForEdge:isVertical ? point.x : point.y];
  1101. if (rowIdx == NSNotFound) return NSNotFound;
  1102. NSUInteger lineIdx0 = _lineRowsIndex[rowIdx];
  1103. NSUInteger lineIdx1 = rowIdx == _rowCount - 1 ? _lines.count - 1 : _lineRowsIndex[rowIdx + 1] - 1;
  1104. if (lineIdx0 == lineIdx1) return lineIdx0;
  1105. CGFloat minDistance = CGFLOAT_MAX;
  1106. NSUInteger minIndex = lineIdx0;
  1107. for (NSUInteger i = lineIdx0; i <= lineIdx1; i++) {
  1108. CGRect bounds = ((YYTextLine *)_lines[i]).bounds;
  1109. if (isVertical) {
  1110. if (bounds.origin.y <= point.y && point.y <= bounds.origin.y + bounds.size.height) return i;
  1111. CGFloat distance;
  1112. if (point.y < bounds.origin.y) {
  1113. distance = bounds.origin.y - point.y;
  1114. } else {
  1115. distance = point.y - (bounds.origin.y + bounds.size.height);
  1116. }
  1117. if (distance < minDistance) {
  1118. minDistance = distance;
  1119. minIndex = i;
  1120. }
  1121. } else {
  1122. if (bounds.origin.x <= point.x && point.x <= bounds.origin.x + bounds.size.width) return i;
  1123. CGFloat distance;
  1124. if (point.x < bounds.origin.x) {
  1125. distance = bounds.origin.x - point.x;
  1126. } else {
  1127. distance = point.x - (bounds.origin.x + bounds.size.width);
  1128. }
  1129. if (distance < minDistance) {
  1130. minDistance = distance;
  1131. minIndex = i;
  1132. }
  1133. }
  1134. }
  1135. return minIndex;
  1136. }
  1137. - (CGFloat)offsetForTextPosition:(NSUInteger)position lineIndex:(NSUInteger)lineIndex {
  1138. if (lineIndex >= _lines.count) return CGFLOAT_MAX;
  1139. YYTextLine *line = _lines[lineIndex];
  1140. CFRange range = CTLineGetStringRange(line.CTLine);
  1141. if (position < range.location || position > range.location + range.length) return CGFLOAT_MAX;
  1142. CGFloat offset = CTLineGetOffsetForStringIndex(line.CTLine, position, NULL);
  1143. return _container.verticalForm ? (offset + line.position.y) : (offset + line.position.x);
  1144. }
  1145. - (NSUInteger)textPositionForPoint:(CGPoint)point lineIndex:(NSUInteger)lineIndex {
  1146. if (lineIndex >= _lines.count) return NSNotFound;
  1147. YYTextLine *line = _lines[lineIndex];
  1148. if (_container.verticalForm) {
  1149. point.x = point.y - line.position.y;
  1150. point.y = 0;
  1151. } else {
  1152. point.x -= line.position.x;
  1153. point.y = 0;
  1154. }
  1155. CFIndex idx = CTLineGetStringIndexForPosition(line.CTLine, point);
  1156. if (idx == kCFNotFound) return NSNotFound;
  1157. /*
  1158. If the emoji contains one or more variant form (such as ☔️ "\u2614\uFE0F")
  1159. and the font size is smaller than 379/15, then each variant form ("\uFE0F")
  1160. will rendered as a single blank glyph behind the emoji glyph. Maybe it's a
  1161. bug in CoreText? Seems iOS8.3 fixes this problem.
  1162. If the point hit the blank glyph, the CTLineGetStringIndexForPosition()
  1163. returns the position before the emoji glyph, but it should returns the
  1164. position after the emoji and variant form.
  1165. Here's a workaround.
  1166. */
  1167. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  1168. for (NSUInteger r = 0, max = CFArrayGetCount(runs); r < max; r++) {
  1169. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  1170. CFRange range = CTRunGetStringRange(run);
  1171. if (range.location <= idx && idx < range.location + range.length) {
  1172. NSUInteger glyphCount = CTRunGetGlyphCount(run);
  1173. if (glyphCount == 0) break;
  1174. CFDictionaryRef attrs = CTRunGetAttributes(run);
  1175. CTFontRef font = CFDictionaryGetValue(attrs, kCTFontAttributeName);
  1176. if (!CTFontContainsColorBitmapGlyphs(font)) break;
  1177. CFIndex indices[glyphCount];
  1178. CGPoint positions[glyphCount];
  1179. CTRunGetStringIndices(run, CFRangeMake(0, glyphCount), indices);
  1180. CTRunGetPositions(run, CFRangeMake(0, glyphCount), positions);
  1181. for (NSUInteger g = 0; g < glyphCount; g++) {
  1182. NSUInteger gIdx = indices[g];
  1183. if (gIdx == idx && g + 1 < glyphCount) {
  1184. CGFloat right = positions[g + 1].x;
  1185. if (point.x < right) break;
  1186. NSUInteger next = indices[g + 1];
  1187. do {
  1188. if (next == range.location + range.length) break;
  1189. unichar c = [_text.string characterAtIndex:next];
  1190. if ((c == 0xFE0E || c == 0xFE0F)) { // unicode variant form for emoji style
  1191. next++;
  1192. } else break;
  1193. }
  1194. while (1);
  1195. if (next != indices[g + 1]) idx = next;
  1196. break;
  1197. }
  1198. }
  1199. break;
  1200. }
  1201. }
  1202. return idx;
  1203. }
  1204. - (YYTextPosition *)closestPositionToPoint:(CGPoint)point {
  1205. BOOL isVertical = _container.verticalForm;
  1206. // When call CTLineGetStringIndexForPosition() on ligature such as 'fi',
  1207. // and the point `hit` the glyph's left edge, it may get the ligature inside offset.
  1208. // I don't know why, maybe it's a bug of CoreText. Try to avoid it.
  1209. if (isVertical) point.y += 0.00001234;
  1210. else point.x += 0.00001234;
  1211. NSUInteger lineIndex = [self closestLineIndexForPoint:point];
  1212. if (lineIndex == NSNotFound) return nil;
  1213. YYTextLine *line = _lines[lineIndex];
  1214. __block NSUInteger position = [self textPositionForPoint:point lineIndex:lineIndex];
  1215. if (position == NSNotFound) position = line.range.location;
  1216. if (position <= _visibleRange.location) {
  1217. return [YYTextPosition positionWithOffset:_visibleRange.location affinity:YYTextAffinityForward];
  1218. } else if (position >= _visibleRange.location + _visibleRange.length) {
  1219. return [YYTextPosition positionWithOffset:_visibleRange.location + _visibleRange.length affinity:YYTextAffinityBackward];
  1220. }
  1221. YYTextAffinity finalAffinity = YYTextAffinityForward;
  1222. BOOL finalAffinityDetected = NO;
  1223. // binding range
  1224. NSRange bindingRange;
  1225. YYTextBinding *binding = [_text attribute:YYTextBindingAttributeName atIndex:position longestEffectiveRange:&bindingRange inRange:NSMakeRange(0, _text.length)];
  1226. if (binding && bindingRange.length > 0) {
  1227. NSUInteger headLineIdx = [self lineIndexForPosition:[YYTextPosition positionWithOffset:bindingRange.location]];
  1228. NSUInteger tailLineIdx = [self lineIndexForPosition:[YYTextPosition positionWithOffset:bindingRange.location + bindingRange.length affinity:YYTextAffinityBackward]];
  1229. if (headLineIdx == lineIndex && lineIndex == tailLineIdx) { // all in same line
  1230. CGFloat left = [self offsetForTextPosition:bindingRange.location lineIndex:lineIndex];
  1231. CGFloat right = [self offsetForTextPosition:bindingRange.location + bindingRange.length lineIndex:lineIndex];
  1232. if (left != CGFLOAT_MAX && right != CGFLOAT_MAX) {
  1233. if (_container.isVerticalForm) {
  1234. if (fabs(point.y - left) < fabs(point.y - right)) {
  1235. position = bindingRange.location;
  1236. finalAffinity = YYTextAffinityForward;
  1237. } else {
  1238. position = bindingRange.location + bindingRange.length;
  1239. finalAffinity = YYTextAffinityBackward;
  1240. }
  1241. } else {
  1242. if (fabs(point.x - left) < fabs(point.x - right)) {
  1243. position = bindingRange.location;
  1244. finalAffinity = YYTextAffinityForward;
  1245. } else {
  1246. position = bindingRange.location + bindingRange.length;
  1247. finalAffinity = YYTextAffinityBackward;
  1248. }
  1249. }
  1250. } else if (left != CGFLOAT_MAX) {
  1251. position = left;
  1252. finalAffinity = YYTextAffinityForward;
  1253. } else if (right != CGFLOAT_MAX) {
  1254. position = right;
  1255. finalAffinity = YYTextAffinityBackward;
  1256. }
  1257. finalAffinityDetected = YES;
  1258. } else if (headLineIdx == lineIndex) {
  1259. CGFloat left = [self offsetForTextPosition:bindingRange.location lineIndex:lineIndex];
  1260. if (left != CGFLOAT_MAX) {
  1261. position = bindingRange.location;
  1262. finalAffinity = YYTextAffinityForward;
  1263. finalAffinityDetected = YES;
  1264. }
  1265. } else if (tailLineIdx == lineIndex) {
  1266. CGFloat right = [self offsetForTextPosition:bindingRange.location + bindingRange.length lineIndex:lineIndex];
  1267. if (right != CGFLOAT_MAX) {
  1268. position = bindingRange.location + bindingRange.length;
  1269. finalAffinity = YYTextAffinityBackward;
  1270. finalAffinityDetected = YES;
  1271. }
  1272. } else {
  1273. BOOL onLeft = NO, onRight = NO;
  1274. if (headLineIdx != NSNotFound && tailLineIdx != NSNotFound) {
  1275. if (abs((int)headLineIdx - (int)lineIndex) < abs((int)tailLineIdx - (int)lineIndex)) onLeft = YES;
  1276. else onRight = YES;
  1277. } else if (headLineIdx != NSNotFound) {
  1278. onLeft = YES;
  1279. } else if (tailLineIdx != NSNotFound) {
  1280. onRight = YES;
  1281. }
  1282. if (onLeft) {
  1283. CGFloat left = [self offsetForTextPosition:bindingRange.location lineIndex:headLineIdx];
  1284. if (left != CGFLOAT_MAX) {
  1285. lineIndex = headLineIdx;
  1286. line = _lines[headLineIdx];
  1287. position = bindingRange.location;
  1288. finalAffinity = YYTextAffinityForward;
  1289. finalAffinityDetected = YES;
  1290. }
  1291. } else if (onRight) {
  1292. CGFloat right = [self offsetForTextPosition:bindingRange.location + bindingRange.length lineIndex:tailLineIdx];
  1293. if (right != CGFLOAT_MAX) {
  1294. lineIndex = tailLineIdx;
  1295. line = _lines[tailLineIdx];
  1296. position = bindingRange.location + bindingRange.length;
  1297. finalAffinity = YYTextAffinityBackward;
  1298. finalAffinityDetected = YES;
  1299. }
  1300. }
  1301. }
  1302. }
  1303. // empty line
  1304. if (line.range.length == 0) {
  1305. BOOL behind = (_lines.count > 1 && lineIndex == _lines.count - 1); //end line
  1306. return [YYTextPosition positionWithOffset:line.range.location affinity:behind ? YYTextAffinityBackward:YYTextAffinityForward];
  1307. }
  1308. // detect whether the line is a linebreak token
  1309. if (line.range.length <= 2) {
  1310. NSString *str = [_text.string substringWithRange:line.range];
  1311. if (YYTextIsLinebreakString(str)) { // an empty line ("\r", "\n", "\r\n")
  1312. return [YYTextPosition positionWithOffset:line.range.location];
  1313. }
  1314. }
  1315. // above whole text frame
  1316. if (lineIndex == 0 && (isVertical ? (point.x > line.right) : (point.y < line.top))) {
  1317. position = 0;
  1318. finalAffinity = YYTextAffinityForward;
  1319. finalAffinityDetected = YES;
  1320. }
  1321. // below whole text frame
  1322. if (lineIndex == _lines.count - 1 && (isVertical ? (point.x < line.left) : (point.y > line.bottom))) {
  1323. position = line.range.location + line.range.length;
  1324. finalAffinity = YYTextAffinityBackward;
  1325. finalAffinityDetected = YES;
  1326. }
  1327. // There must be at least one non-linebreak char,
  1328. // ignore the linebreak characters at line end if exists.
  1329. if (position >= line.range.location + line.range.length - 1) {
  1330. if (position > line.range.location) {
  1331. unichar c1 = [_text.string characterAtIndex:position - 1];
  1332. if (YYTextIsLinebreakChar(c1)) {
  1333. position--;
  1334. if (position > line.range.location) {
  1335. unichar c0 = [_text.string characterAtIndex:position - 1];
  1336. if (YYTextIsLinebreakChar(c0)) {
  1337. position--;
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. if (position == line.range.location) {
  1344. return [YYTextPosition positionWithOffset:position];
  1345. }
  1346. if (position == line.range.location + line.range.length) {
  1347. return [YYTextPosition positionWithOffset:position affinity:YYTextAffinityBackward];
  1348. }
  1349. [self _insideComposedCharacterSequences:line position:position block: ^(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next) {
  1350. if (isVertical) {
  1351. position = fabs(left - point.y) < fabs(right - point.y) < (right ? prev : next);
  1352. } else {
  1353. position = fabs(left - point.x) < fabs(right - point.x) < (right ? prev : next);
  1354. }
  1355. }];
  1356. [self _insideEmoji:line position:position block: ^(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next) {
  1357. if (isVertical) {
  1358. position = fabs(left - point.y) < fabs(right - point.y) < (right ? prev : next);
  1359. } else {
  1360. position = fabs(left - point.x) < fabs(right - point.x) < (right ? prev : next);
  1361. }
  1362. }];
  1363. if (position < _visibleRange.location) position = _visibleRange.location;
  1364. else if (position > _visibleRange.location + _visibleRange.length) position = _visibleRange.location + _visibleRange.length;
  1365. if (!finalAffinityDetected) {
  1366. CGFloat ofs = [self offsetForTextPosition:position lineIndex:lineIndex];
  1367. if (ofs != CGFLOAT_MAX) {
  1368. BOOL RTL = [self _isRightToLeftInLine:line atPoint:point];
  1369. if (position >= line.range.location + line.range.length) {
  1370. finalAffinity = RTL ? YYTextAffinityForward : YYTextAffinityBackward;
  1371. } else if (position <= line.range.location) {
  1372. finalAffinity = RTL ? YYTextAffinityBackward : YYTextAffinityForward;
  1373. } else {
  1374. finalAffinity = (ofs < (isVertical ? point.y : point.x) && !RTL) ? YYTextAffinityForward : YYTextAffinityBackward;
  1375. }
  1376. }
  1377. }
  1378. return [YYTextPosition positionWithOffset:position affinity:finalAffinity];
  1379. }
  1380. - (YYTextPosition *)positionForPoint:(CGPoint)point
  1381. oldPosition:(YYTextPosition *)oldPosition
  1382. otherPosition:(YYTextPosition *)otherPosition {
  1383. if (!oldPosition || !otherPosition) {
  1384. return oldPosition;
  1385. }
  1386. YYTextPosition *newPos = [self closestPositionToPoint:point];
  1387. if (!newPos) return oldPosition;
  1388. if ([newPos compare:otherPosition] == [oldPosition compare:otherPosition] &&
  1389. newPos.offset != otherPosition.offset) {
  1390. return newPos;
  1391. }
  1392. NSUInteger lineIndex = [self lineIndexForPosition:otherPosition];
  1393. if (lineIndex == NSNotFound) return oldPosition;
  1394. YYTextLine *line = _lines[lineIndex];
  1395. YYRowEdge vertical = _lineRowsEdge[line.row];
  1396. if (_container.verticalForm) {
  1397. point.x = (vertical.head + vertical.foot) * 0.5;
  1398. } else {
  1399. point.y = (vertical.head + vertical.foot) * 0.5;
  1400. }
  1401. newPos = [self closestPositionToPoint:point];
  1402. if ([newPos compare:otherPosition] == [oldPosition compare:otherPosition] &&
  1403. newPos.offset != otherPosition.offset) {
  1404. return newPos;
  1405. }
  1406. if (_container.isVerticalForm) {
  1407. if ([oldPosition compare:otherPosition] == NSOrderedAscending) { // search backward
  1408. YYTextRange *range = [self textRangeByExtendingPosition:otherPosition inDirection:UITextLayoutDirectionUp offset:1];
  1409. if (range) return range.start;
  1410. } else { // search forward
  1411. YYTextRange *range = [self textRangeByExtendingPosition:otherPosition inDirection:UITextLayoutDirectionDown offset:1];
  1412. if (range) return range.end;
  1413. }
  1414. } else {
  1415. if ([oldPosition compare:otherPosition] == NSOrderedAscending) { // search backward
  1416. YYTextRange *range = [self textRangeByExtendingPosition:otherPosition inDirection:UITextLayoutDirectionLeft offset:1];
  1417. if (range) return range.start;
  1418. } else { // search forward
  1419. YYTextRange *range = [self textRangeByExtendingPosition:otherPosition inDirection:UITextLayoutDirectionRight offset:1];
  1420. if (range) return range.end;
  1421. }
  1422. }
  1423. return oldPosition;
  1424. }
  1425. - (YYTextRange *)textRangeAtPoint:(CGPoint)point {
  1426. NSUInteger lineIndex = [self lineIndexForPoint:point];
  1427. if (lineIndex == NSNotFound) return nil;
  1428. NSUInteger textPosition = [self textPositionForPoint:point lineIndex:[self lineIndexForPoint:point]];
  1429. if (textPosition == NSNotFound) return nil;
  1430. YYTextPosition *pos = [self closestPositionToPoint:point];
  1431. if (!pos) return nil;
  1432. // get write direction
  1433. BOOL RTL = [self _isRightToLeftInLine:_lines[lineIndex] atPoint:point];
  1434. CGRect rect = [self caretRectForPosition:pos];
  1435. if (CGRectIsNull(rect)) return nil;
  1436. if (_container.verticalForm) {
  1437. YYTextRange *range = [self textRangeByExtendingPosition:pos inDirection:(rect.origin.y >= point.y && !RTL) ? UITextLayoutDirectionUp:UITextLayoutDirectionDown offset:1];
  1438. return range;
  1439. } else {
  1440. YYTextRange *range = [self textRangeByExtendingPosition:pos inDirection:(rect.origin.x >= point.x && !RTL) ? UITextLayoutDirectionLeft:UITextLayoutDirectionRight offset:1];
  1441. return range;
  1442. }
  1443. }
  1444. - (YYTextRange *)closestTextRangeAtPoint:(CGPoint)point {
  1445. YYTextPosition *pos = [self closestPositionToPoint:point];
  1446. if (!pos) return nil;
  1447. NSUInteger lineIndex = [self lineIndexForPosition:pos];
  1448. if (lineIndex == NSNotFound) return nil;
  1449. YYTextLine *line = _lines[lineIndex];
  1450. BOOL RTL = [self _isRightToLeftInLine:line atPoint:point];
  1451. CGRect rect = [self caretRectForPosition:pos];
  1452. if (CGRectIsNull(rect)) return nil;
  1453. UITextLayoutDirection direction = UITextLayoutDirectionRight;
  1454. if (pos.offset >= line.range.location + line.range.length) {
  1455. if (direction != RTL) {
  1456. direction = _container.verticalForm ? UITextLayoutDirectionUp : UITextLayoutDirectionLeft;
  1457. } else {
  1458. direction = _container.verticalForm ? UITextLayoutDirectionDown : UITextLayoutDirectionRight;
  1459. }
  1460. } else if (pos.offset <= line.range.location) {
  1461. if (direction != RTL) {
  1462. direction = _container.verticalForm ? UITextLayoutDirectionDown : UITextLayoutDirectionRight;
  1463. } else {
  1464. direction = _container.verticalForm ? UITextLayoutDirectionUp : UITextLayoutDirectionLeft;
  1465. }
  1466. } else {
  1467. if (_container.verticalForm) {
  1468. direction = (rect.origin.y >= point.y && !RTL) ? UITextLayoutDirectionUp:UITextLayoutDirectionDown;
  1469. } else {
  1470. direction = (rect.origin.x >= point.x && !RTL) ? UITextLayoutDirectionLeft:UITextLayoutDirectionRight;
  1471. }
  1472. }
  1473. YYTextRange *range = [self textRangeByExtendingPosition:pos inDirection:direction offset:1];
  1474. return range;
  1475. }
  1476. - (YYTextRange *)textRangeByExtendingPosition:(YYTextPosition *)position {
  1477. NSUInteger visibleStart = _visibleRange.location;
  1478. NSUInteger visibleEnd = _visibleRange.location + _visibleRange.length;
  1479. if (!position) return nil;
  1480. if (position.offset < visibleStart || position.offset > visibleEnd) return nil;
  1481. // head or tail, returns immediately
  1482. if (position.offset == visibleStart) {
  1483. return [YYTextRange rangeWithRange:NSMakeRange(position.offset, 0)];
  1484. } else if (position.offset == visibleEnd) {
  1485. return [YYTextRange rangeWithRange:NSMakeRange(position.offset, 0) affinity:YYTextAffinityBackward];
  1486. }
  1487. // binding range
  1488. NSRange tRange;
  1489. YYTextBinding *binding = [_text attribute:YYTextBindingAttributeName atIndex:position.offset longestEffectiveRange:&tRange inRange:_visibleRange];
  1490. if (binding && tRange.length > 0 && tRange.location < position.offset) {
  1491. return [YYTextRange rangeWithRange:tRange];
  1492. }
  1493. // inside emoji or composed character sequences
  1494. NSUInteger lineIndex = [self lineIndexForPosition:position];
  1495. if (lineIndex != NSNotFound) {
  1496. __block NSUInteger _prev, _next;
  1497. BOOL emoji = NO, seq = NO;
  1498. YYTextLine *line = _lines[lineIndex];
  1499. emoji = [self _insideEmoji:line position:position.offset block: ^(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next) {
  1500. _prev = prev;
  1501. _next = next;
  1502. }];
  1503. if (!emoji) {
  1504. seq = [self _insideComposedCharacterSequences:line position:position.offset block: ^(CGFloat left, CGFloat right, NSUInteger prev, NSUInteger next) {
  1505. _prev = prev;
  1506. _next = next;
  1507. }];
  1508. }
  1509. if (emoji || seq) {
  1510. return [YYTextRange rangeWithRange:NSMakeRange(_prev, _next - _prev)];
  1511. }
  1512. }
  1513. // inside linebreak '\r\n'
  1514. if (position.offset > visibleStart && position.offset < visibleEnd) {
  1515. unichar c0 = [_text.string characterAtIndex:position.offset - 1];
  1516. if ((c0 == '\r') && position.offset < visibleEnd) {
  1517. unichar c1 = [_text.string characterAtIndex:position.offset];
  1518. if (c1 == '\n') {
  1519. return [YYTextRange rangeWithStart:[YYTextPosition positionWithOffset:position.offset - 1] end:[YYTextPosition positionWithOffset:position.offset + 1]];
  1520. }
  1521. }
  1522. if (YYTextIsLinebreakChar(c0) && position.affinity == YYTextAffinityBackward) {
  1523. NSString *str = [_text.string substringToIndex:position.offset];
  1524. NSUInteger len = YYTextLinebreakTailLength(str);
  1525. return [YYTextRange rangeWithStart:[YYTextPosition positionWithOffset:position.offset - len] end:[YYTextPosition positionWithOffset:position.offset]];
  1526. }
  1527. }
  1528. return [YYTextRange rangeWithRange:NSMakeRange(position.offset, 0) affinity:position.affinity];
  1529. }
  1530. - (YYTextRange *)textRangeByExtendingPosition:(YYTextPosition *)position
  1531. inDirection:(UITextLayoutDirection)direction
  1532. offset:(NSInteger)offset {
  1533. NSInteger visibleStart = _visibleRange.location;
  1534. NSInteger visibleEnd = _visibleRange.location + _visibleRange.length;
  1535. if (!position) return nil;
  1536. if (position.offset < visibleStart || position.offset > visibleEnd) return nil;
  1537. if (offset == 0) return [self textRangeByExtendingPosition:position];
  1538. BOOL isVerticalForm = _container.verticalForm;
  1539. BOOL verticalMove, forwardMove;
  1540. if (isVerticalForm) {
  1541. verticalMove = direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionRight;
  1542. forwardMove = direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionDown;
  1543. } else {
  1544. verticalMove = direction == UITextLayoutDirectionUp || direction == UITextLayoutDirectionDown;
  1545. forwardMove = direction == UITextLayoutDirectionDown || direction == UITextLayoutDirectionRight;
  1546. }
  1547. if (offset < 0) {
  1548. forwardMove = !forwardMove;
  1549. offset = -offset;
  1550. }
  1551. // head or tail, returns immediately
  1552. if (!forwardMove && position.offset == visibleStart) {
  1553. return [YYTextRange rangeWithRange:NSMakeRange(_visibleRange.location, 0)];
  1554. } else if (forwardMove && position.offset == visibleEnd) {
  1555. return [YYTextRange rangeWithRange:NSMakeRange(position.offset, 0) affinity:YYTextAffinityBackward];
  1556. }
  1557. // extend from position
  1558. YYTextRange *fromRange = [self textRangeByExtendingPosition:position];
  1559. if (!fromRange) return nil;
  1560. YYTextRange *allForward = [YYTextRange rangeWithStart:fromRange.start end:[YYTextPosition positionWithOffset:visibleEnd]];
  1561. YYTextRange *allBackward = [YYTextRange rangeWithStart:[YYTextPosition positionWithOffset:visibleStart] end:fromRange.end];
  1562. if (verticalMove) { // up/down in text layout
  1563. NSInteger lineIndex = [self lineIndexForPosition:position];
  1564. if (lineIndex == NSNotFound) return nil;
  1565. YYTextLine *line = _lines[lineIndex];
  1566. NSInteger moveToRowIndex = (NSInteger)line.row + (forwardMove ? offset : -offset);
  1567. if (moveToRowIndex < 0) return allBackward;
  1568. else if (moveToRowIndex >= (NSInteger)_rowCount) return allForward;
  1569. CGFloat ofs = [self offsetForTextPosition:position.offset lineIndex:lineIndex];
  1570. if (ofs == CGFLOAT_MAX) return nil;
  1571. NSUInteger moveToLineFirstIndex = [self lineIndexForRow:moveToRowIndex];
  1572. NSUInteger moveToLineCount = [self lineCountForRow:moveToRowIndex];
  1573. if (moveToLineFirstIndex == NSNotFound || moveToLineCount == NSNotFound || moveToLineCount == 0) return nil;
  1574. CGFloat mostLeft = CGFLOAT_MAX, mostRight = -CGFLOAT_MAX;
  1575. YYTextLine *mostLeftLine = nil, *mostRightLine = nil;
  1576. NSUInteger insideIndex = NSNotFound;
  1577. for (NSUInteger i = 0; i < moveToLineCount; i++) {
  1578. NSUInteger lineIndex = moveToLineFirstIndex + i;
  1579. YYTextLine *line = _lines[lineIndex];
  1580. if (isVerticalForm) {
  1581. if (line.top <= ofs && ofs <= line.bottom) {
  1582. insideIndex = line.index;
  1583. break;
  1584. }
  1585. if (line.top < mostLeft) {
  1586. mostLeft = line.top;
  1587. mostLeftLine = line;
  1588. }
  1589. if (line.bottom > mostRight) {
  1590. mostRight = line.bottom;
  1591. mostRightLine = line;
  1592. }
  1593. } else {
  1594. if (line.left <= ofs && ofs <= line.right) {
  1595. insideIndex = line.index;
  1596. break;
  1597. }
  1598. if (line.left < mostLeft) {
  1599. mostLeft = line.left;
  1600. mostLeftLine = line;
  1601. }
  1602. if (line.right > mostRight) {
  1603. mostRight = line.right;
  1604. mostRightLine = line;
  1605. }
  1606. }
  1607. }
  1608. BOOL afinityEdge = NO;
  1609. if (insideIndex == NSNotFound) {
  1610. if (ofs <= mostLeft) {
  1611. insideIndex = mostLeftLine.index;
  1612. } else {
  1613. insideIndex = mostRightLine.index;
  1614. }
  1615. afinityEdge = YES;
  1616. }
  1617. YYTextLine *insideLine = _lines[insideIndex];
  1618. NSUInteger pos;
  1619. if (isVerticalForm) {
  1620. pos = [self textPositionForPoint:CGPointMake(insideLine.position.x, ofs) lineIndex:insideIndex];
  1621. } else {
  1622. pos = [self textPositionForPoint:CGPointMake(ofs, insideLine.position.y) lineIndex:insideIndex];
  1623. }
  1624. if (pos == NSNotFound) return nil;
  1625. YYTextPosition *extPos;
  1626. if (afinityEdge) {
  1627. if (pos == insideLine.range.location + insideLine.range.length) {
  1628. NSString *subStr = [_text.string substringWithRange:insideLine.range];
  1629. NSUInteger lineBreakLen = YYTextLinebreakTailLength(subStr);
  1630. extPos = [YYTextPosition positionWithOffset:pos - lineBreakLen];
  1631. } else {
  1632. extPos = [YYTextPosition positionWithOffset:pos];
  1633. }
  1634. } else {
  1635. extPos = [YYTextPosition positionWithOffset:pos];
  1636. }
  1637. YYTextRange *ext = [self textRangeByExtendingPosition:extPos];
  1638. if (!ext) return nil;
  1639. if (forwardMove) {
  1640. return [YYTextRange rangeWithStart:fromRange.start end:ext.end];
  1641. } else {
  1642. return [YYTextRange rangeWithStart:ext.start end:fromRange.end];
  1643. }
  1644. } else { // left/right in text layout
  1645. YYTextPosition *toPosition = [YYTextPosition positionWithOffset:position.offset + (forwardMove ? offset : -offset)];
  1646. if (toPosition.offset <= visibleStart) return allBackward;
  1647. else if (toPosition.offset >= visibleEnd) return allForward;
  1648. YYTextRange *toRange = [self textRangeByExtendingPosition:toPosition];
  1649. if (!toRange) return nil;
  1650. NSInteger start = MIN(fromRange.start.offset, toRange.start.offset);
  1651. NSInteger end = MAX(fromRange.end.offset, toRange.end.offset);
  1652. return [YYTextRange rangeWithRange:NSMakeRange(start, end - start)];
  1653. }
  1654. }
  1655. - (NSUInteger)lineIndexForPosition:(YYTextPosition *)position {
  1656. if (!position) return NSNotFound;
  1657. if (_lines.count == 0) return NSNotFound;
  1658. NSUInteger location = position.offset;
  1659. NSInteger lo = 0, hi = _lines.count - 1, mid = 0;
  1660. if (position.affinity == YYTextAffinityBackward) {
  1661. while (lo <= hi) {
  1662. mid = (lo + hi) / 2;
  1663. YYTextLine *line = _lines[mid];
  1664. NSRange range = line.range;
  1665. if (range.location < location && location <= range.location + range.length) {
  1666. return mid;
  1667. }
  1668. if (location <= range.location) {
  1669. hi = mid - 1;
  1670. } else {
  1671. lo = mid + 1;
  1672. }
  1673. }
  1674. } else {
  1675. while (lo <= hi) {
  1676. mid = (lo + hi) / 2;
  1677. YYTextLine *line = _lines[mid];
  1678. NSRange range = line.range;
  1679. if (range.location <= location && location < range.location + range.length) {
  1680. return mid;
  1681. }
  1682. if (location < range.location) {
  1683. hi = mid - 1;
  1684. } else {
  1685. lo = mid + 1;
  1686. }
  1687. }
  1688. }
  1689. return NSNotFound;
  1690. }
  1691. - (CGPoint)linePositionForPosition:(YYTextPosition *)position {
  1692. NSUInteger lineIndex = [self lineIndexForPosition:position];
  1693. if (lineIndex == NSNotFound) return CGPointZero;
  1694. YYTextLine *line = _lines[lineIndex];
  1695. CGFloat offset = [self offsetForTextPosition:position.offset lineIndex:lineIndex];
  1696. if (offset == CGFLOAT_MAX) return CGPointZero;
  1697. if (_container.verticalForm) {
  1698. return CGPointMake(line.position.x, offset);
  1699. } else {
  1700. return CGPointMake(offset, line.position.y);
  1701. }
  1702. }
  1703. - (CGRect)caretRectForPosition:(YYTextPosition *)position {
  1704. NSUInteger lineIndex = [self lineIndexForPosition:position];
  1705. if (lineIndex == NSNotFound) return CGRectNull;
  1706. YYTextLine *line = _lines[lineIndex];
  1707. CGFloat offset = [self offsetForTextPosition:position.offset lineIndex:lineIndex];
  1708. if (offset == CGFLOAT_MAX) return CGRectNull;
  1709. if (_container.verticalForm) {
  1710. return CGRectMake(line.bounds.origin.x, offset, line.bounds.size.width, 0);
  1711. } else {
  1712. return CGRectMake(offset, line.bounds.origin.y, 0, line.bounds.size.height);
  1713. }
  1714. }
  1715. - (CGRect)firstRectForRange:(YYTextRange *)range {
  1716. range = [self _correctedRangeWithEdge:range];
  1717. NSUInteger startLineIndex = [self lineIndexForPosition:range.start];
  1718. NSUInteger endLineIndex = [self lineIndexForPosition:range.end];
  1719. if (startLineIndex == NSNotFound || endLineIndex == NSNotFound) return CGRectNull;
  1720. if (startLineIndex > endLineIndex) return CGRectNull;
  1721. YYTextLine *startLine = _lines[startLineIndex];
  1722. YYTextLine *endLine = _lines[endLineIndex];
  1723. NSMutableArray *lines = [NSMutableArray new];
  1724. for (NSUInteger i = startLineIndex; i <= startLineIndex; i++) {
  1725. YYTextLine *line = _lines[i];
  1726. if (line.row != startLine.row) break;
  1727. [lines addObject:line];
  1728. }
  1729. if (_container.verticalForm) {
  1730. if (lines.count == 1) {
  1731. CGFloat top = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1732. CGFloat bottom;
  1733. if (startLine == endLine) {
  1734. bottom = [self offsetForTextPosition:range.end.offset lineIndex:startLineIndex];
  1735. } else {
  1736. bottom = startLine.bottom;
  1737. }
  1738. if (top == CGFLOAT_MAX || bottom == CGFLOAT_MAX) return CGRectNull;
  1739. if (top > bottom) YY_SWAP(top, bottom);
  1740. return CGRectMake(startLine.left, top, startLine.width, bottom - top);
  1741. } else {
  1742. CGFloat top = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1743. CGFloat bottom = startLine.bottom;
  1744. if (top == CGFLOAT_MAX || bottom == CGFLOAT_MAX) return CGRectNull;
  1745. if (top > bottom) YY_SWAP(top, bottom);
  1746. CGRect rect = CGRectMake(startLine.left, top, startLine.width, bottom - top);
  1747. for (NSUInteger i = 1; i < lines.count; i++) {
  1748. YYTextLine *line = lines[i];
  1749. rect = CGRectUnion(rect, line.bounds);
  1750. }
  1751. return rect;
  1752. }
  1753. } else {
  1754. if (lines.count == 1) {
  1755. CGFloat left = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1756. CGFloat right;
  1757. if (startLine == endLine) {
  1758. right = [self offsetForTextPosition:range.end.offset lineIndex:startLineIndex];
  1759. } else {
  1760. right = startLine.right;
  1761. }
  1762. if (left == CGFLOAT_MAX || right == CGFLOAT_MAX) return CGRectNull;
  1763. if (left > right) YY_SWAP(left, right);
  1764. return CGRectMake(left, startLine.top, right - left, startLine.height);
  1765. } else {
  1766. CGFloat left = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1767. CGFloat right = startLine.right;
  1768. if (left == CGFLOAT_MAX || right == CGFLOAT_MAX) return CGRectNull;
  1769. if (left > right) YY_SWAP(left, right);
  1770. CGRect rect = CGRectMake(left, startLine.top, right - left, startLine.height);
  1771. for (NSUInteger i = 1; i < lines.count; i++) {
  1772. YYTextLine *line = lines[i];
  1773. rect = CGRectUnion(rect, line.bounds);
  1774. }
  1775. return rect;
  1776. }
  1777. }
  1778. }
  1779. - (CGRect)rectForRange:(YYTextRange *)range {
  1780. NSArray *rects = [self selectionRectsForRange:range];
  1781. if (rects.count == 0) return CGRectNull;
  1782. CGRect rectUnion = ((YYTextSelectionRect *)rects.firstObject).rect;
  1783. for (NSUInteger i = 1; i < rects.count; i++) {
  1784. YYTextSelectionRect *rect = rects[i];
  1785. rectUnion = CGRectUnion(rectUnion, rect.rect);
  1786. }
  1787. return rectUnion;
  1788. }
  1789. - (NSArray *)selectionRectsForRange:(YYTextRange *)range {
  1790. range = [self _correctedRangeWithEdge:range];
  1791. BOOL isVertical = _container.verticalForm;
  1792. NSMutableArray *rects = [NSMutableArray array];
  1793. if (!range) return rects;
  1794. NSUInteger startLineIndex = [self lineIndexForPosition:range.start];
  1795. NSUInteger endLineIndex = [self lineIndexForPosition:range.end];
  1796. if (startLineIndex == NSNotFound || endLineIndex == NSNotFound) return rects;
  1797. if (startLineIndex > endLineIndex) YY_SWAP(startLineIndex, endLineIndex);
  1798. YYTextLine *startLine = _lines[startLineIndex];
  1799. YYTextLine *endLine = _lines[endLineIndex];
  1800. CGFloat offsetStart = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1801. CGFloat offsetEnd = [self offsetForTextPosition:range.end.offset lineIndex:endLineIndex];
  1802. YYTextSelectionRect *start = [YYTextSelectionRect new];
  1803. if (isVertical) {
  1804. start.rect = CGRectMake(startLine.left, offsetStart, startLine.width, 0);
  1805. } else {
  1806. start.rect = CGRectMake(offsetStart, startLine.top, 0, startLine.height);
  1807. }
  1808. start.containsStart = YES;
  1809. start.isVertical = isVertical;
  1810. [rects addObject:start];
  1811. YYTextSelectionRect *end = [YYTextSelectionRect new];
  1812. if (isVertical) {
  1813. end.rect = CGRectMake(endLine.left, offsetEnd, endLine.width, 0);
  1814. } else {
  1815. end.rect = CGRectMake(offsetEnd, endLine.top, 0, endLine.height);
  1816. }
  1817. end.containsEnd = YES;
  1818. end.isVertical = isVertical;
  1819. [rects addObject:end];
  1820. if (startLine.row == endLine.row) { // same row
  1821. if (offsetStart > offsetEnd) YY_SWAP(offsetStart, offsetEnd);
  1822. YYTextSelectionRect *rect = [YYTextSelectionRect new];
  1823. if (isVertical) {
  1824. rect.rect = CGRectMake(startLine.bounds.origin.x, offsetStart, MAX(startLine.width, endLine.width), offsetEnd - offsetStart);
  1825. } else {
  1826. rect.rect = CGRectMake(offsetStart, startLine.bounds.origin.y, offsetEnd - offsetStart, MAX(startLine.height, endLine.height));
  1827. }
  1828. rect.isVertical = isVertical;
  1829. [rects addObject:rect];
  1830. } else { // more than one row
  1831. // start line select rect
  1832. YYTextSelectionRect *topRect = [YYTextSelectionRect new];
  1833. topRect.isVertical = isVertical;
  1834. CGFloat topOffset = [self offsetForTextPosition:range.start.offset lineIndex:startLineIndex];
  1835. CTRunRef topRun = [self _runForLine:startLine position:range.start];
  1836. if (topRun && (CTRunGetStatus(topRun) & kCTRunStatusRightToLeft)) {
  1837. if (isVertical) {
  1838. topRect.rect = CGRectMake(startLine.left, _container.path ? startLine.top : _container.insets.top, startLine.width, topOffset - startLine.top);
  1839. } else {
  1840. topRect.rect = CGRectMake(_container.path ? startLine.left : _container.insets.left, startLine.top, topOffset - startLine.left, startLine.height);
  1841. }
  1842. topRect.writingDirection = UITextWritingDirectionRightToLeft;
  1843. } else {
  1844. if (isVertical) {
  1845. topRect.rect = CGRectMake(startLine.left, topOffset, startLine.width, (_container.path ? startLine.bottom : _container.size.height - _container.insets.bottom) - topOffset);
  1846. } else {
  1847. topRect.rect = CGRectMake(topOffset, startLine.top, (_container.path ? startLine.right : _container.size.width - _container.insets.right) - topOffset, startLine.height);
  1848. }
  1849. }
  1850. [rects addObject:topRect];
  1851. // end line select rect
  1852. YYTextSelectionRect *bottomRect = [YYTextSelectionRect new];
  1853. bottomRect.isVertical = isVertical;
  1854. CGFloat bottomOffset = [self offsetForTextPosition:range.end.offset lineIndex:endLineIndex];
  1855. CTRunRef bottomRun = [self _runForLine:endLine position:range.end];
  1856. if (bottomRun && (CTRunGetStatus(bottomRun) & kCTRunStatusRightToLeft)) {
  1857. if (isVertical) {
  1858. bottomRect.rect = CGRectMake(endLine.left, bottomOffset, endLine.width, (_container.path ? endLine.bottom : _container.size.height - _container.insets.bottom) - bottomOffset);
  1859. } else {
  1860. bottomRect.rect = CGRectMake(bottomOffset, endLine.top, (_container.path ? endLine.right : _container.size.width - _container.insets.right) - bottomOffset, endLine.height);
  1861. }
  1862. bottomRect.writingDirection = UITextWritingDirectionRightToLeft;
  1863. } else {
  1864. if (isVertical) {
  1865. CGFloat top = _container.path ? endLine.top : _container.insets.top;
  1866. bottomRect.rect = CGRectMake(endLine.left, top, endLine.width, bottomOffset - top);
  1867. } else {
  1868. CGFloat left = _container.path ? endLine.left : _container.insets.left;
  1869. bottomRect.rect = CGRectMake(left, endLine.top, bottomOffset - left, endLine.height);
  1870. }
  1871. }
  1872. [rects addObject:bottomRect];
  1873. if (endLineIndex - startLineIndex >= 2) {
  1874. CGRect r = CGRectZero;
  1875. BOOL startLineDetected = NO;
  1876. for (NSUInteger l = startLineIndex + 1; l < endLineIndex; l++) {
  1877. YYTextLine *line = _lines[l];
  1878. if (line.row == startLine.row || line.row == endLine.row) continue;
  1879. if (!startLineDetected) {
  1880. r = line.bounds;
  1881. startLineDetected = YES;
  1882. } else {
  1883. r = CGRectUnion(r, line.bounds);
  1884. }
  1885. }
  1886. if (startLineDetected) {
  1887. if (isVertical) {
  1888. if (!_container.path) {
  1889. r.origin.y = _container.insets.top;
  1890. r.size.height = _container.size.height - _container.insets.bottom - _container.insets.top;
  1891. }
  1892. r.size.width = CGRectGetMinX(topRect.rect) - CGRectGetMaxX(bottomRect.rect);
  1893. r.origin.x = CGRectGetMaxX(bottomRect.rect);
  1894. } else {
  1895. if (!_container.path) {
  1896. r.origin.x = _container.insets.left;
  1897. r.size.width = _container.size.width - _container.insets.right - _container.insets.left;
  1898. }
  1899. r.origin.y = CGRectGetMaxY(topRect.rect);
  1900. r.size.height = bottomRect.rect.origin.y - r.origin.y;
  1901. }
  1902. YYTextSelectionRect *rect = [YYTextSelectionRect new];
  1903. rect.rect = r;
  1904. rect.isVertical = isVertical;
  1905. [rects addObject:rect];
  1906. }
  1907. } else {
  1908. if (isVertical) {
  1909. CGRect r0 = bottomRect.rect;
  1910. CGRect r1 = topRect.rect;
  1911. CGFloat mid = (CGRectGetMaxX(r0) + CGRectGetMinX(r1)) * 0.5;
  1912. r0.size.width = mid - r0.origin.x;
  1913. CGFloat r1ofs = r1.origin.x - mid;
  1914. r1.origin.x -= r1ofs;
  1915. r1.size.width += r1ofs;
  1916. topRect.rect = r1;
  1917. bottomRect.rect = r0;
  1918. } else {
  1919. CGRect r0 = topRect.rect;
  1920. CGRect r1 = bottomRect.rect;
  1921. CGFloat mid = (CGRectGetMaxY(r0) + CGRectGetMinY(r1)) * 0.5;
  1922. r0.size.height = mid - r0.origin.y;
  1923. CGFloat r1ofs = r1.origin.y - mid;
  1924. r1.origin.y -= r1ofs;
  1925. r1.size.height += r1ofs;
  1926. topRect.rect = r0;
  1927. bottomRect.rect = r1;
  1928. }
  1929. }
  1930. }
  1931. return rects;
  1932. }
  1933. - (NSArray *)selectionRectsWithoutStartAndEndForRange:(YYTextRange *)range {
  1934. NSMutableArray *rects = [self selectionRectsForRange:range].mutableCopy;
  1935. for (NSInteger i = 0, max = rects.count; i < max; i++) {
  1936. YYTextSelectionRect *rect = rects[i];
  1937. if (rect.containsStart || rect.containsEnd) {
  1938. [rects removeObjectAtIndex:i];
  1939. i--;
  1940. max--;
  1941. }
  1942. }
  1943. return rects;
  1944. }
  1945. - (NSArray *)selectionRectsWithOnlyStartAndEndForRange:(YYTextRange *)range {
  1946. NSMutableArray *rects = [self selectionRectsForRange:range].mutableCopy;
  1947. for (NSInteger i = 0, max = rects.count; i < max; i++) {
  1948. YYTextSelectionRect *rect = rects[i];
  1949. if (!rect.containsStart && !rect.containsEnd) {
  1950. [rects removeObjectAtIndex:i];
  1951. i--;
  1952. max--;
  1953. }
  1954. }
  1955. return rects;
  1956. }
  1957. #pragma mark - Draw
  1958. typedef NS_OPTIONS(NSUInteger, YYTextDecorationType) {
  1959. YYTextDecorationTypeUnderline = 1 << 0,
  1960. YYTextDecorationTypeStrikethrough = 1 << 1,
  1961. };
  1962. typedef NS_OPTIONS(NSUInteger, YYTextBorderType) {
  1963. YYTextBorderTypeBackgound = 1 << 0,
  1964. YYTextBorderTypeNormal = 1 << 1,
  1965. };
  1966. static CGRect YYTextMergeRectInSameLine(CGRect rect1, CGRect rect2, BOOL isVertical) {
  1967. if (isVertical) {
  1968. CGFloat top = MIN(rect1.origin.y, rect2.origin.y);
  1969. CGFloat bottom = MAX(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height);
  1970. CGFloat width = MAX(rect1.size.width, rect2.size.width);
  1971. return CGRectMake(rect1.origin.x, top, width, bottom - top);
  1972. } else {
  1973. CGFloat left = MIN(rect1.origin.x, rect2.origin.x);
  1974. CGFloat right = MAX(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width);
  1975. CGFloat height = MAX(rect1.size.height, rect2.size.height);
  1976. return CGRectMake(left, rect1.origin.y, right - left, height);
  1977. }
  1978. }
  1979. static void YYTextGetRunsMaxMetric(CFArrayRef runs, CGFloat *xHeight, CGFloat *underlinePosition, CGFloat *lineThickness) {
  1980. CGFloat maxXHeight = 0;
  1981. CGFloat maxUnderlinePos = 0;
  1982. CGFloat maxLineThickness = 0;
  1983. for (NSUInteger i = 0, max = CFArrayGetCount(runs); i < max; i++) {
  1984. CTRunRef run = CFArrayGetValueAtIndex(runs, i);
  1985. CFDictionaryRef attrs = CTRunGetAttributes(run);
  1986. if (attrs) {
  1987. CTFontRef font = CFDictionaryGetValue(attrs, kCTFontAttributeName);
  1988. if (font) {
  1989. CGFloat xHeight = CTFontGetXHeight(font);
  1990. if (xHeight > maxXHeight) maxXHeight = xHeight;
  1991. CGFloat underlinePos = CTFontGetUnderlinePosition(font);
  1992. if (underlinePos < maxUnderlinePos) maxUnderlinePos = underlinePos;
  1993. CGFloat lineThickness = CTFontGetUnderlineThickness(font);
  1994. if (lineThickness > maxLineThickness) maxLineThickness = lineThickness;
  1995. }
  1996. }
  1997. }
  1998. if (xHeight) *xHeight = maxXHeight;
  1999. if (underlinePosition) *underlinePosition = maxUnderlinePos;
  2000. if (lineThickness) *lineThickness = maxLineThickness;
  2001. }
  2002. static void YYTextDrawRun(YYTextLine *line, CTRunRef run, CGContextRef context, CGSize size, BOOL isVertical, NSArray *runRanges, CGFloat verticalOffset) {
  2003. CGAffineTransform runTextMatrix = CTRunGetTextMatrix(run);
  2004. BOOL runTextMatrixIsID = CGAffineTransformIsIdentity(runTextMatrix);
  2005. CFDictionaryRef runAttrs = CTRunGetAttributes(run);
  2006. NSValue *glyphTransformValue = CFDictionaryGetValue(runAttrs, (__bridge const void *)(YYTextGlyphTransformAttributeName));
  2007. if (!isVertical && !glyphTransformValue) { // draw run
  2008. if (!runTextMatrixIsID) {
  2009. CGContextSaveGState(context);
  2010. CGAffineTransform trans = CGContextGetTextMatrix(context);
  2011. CGContextSetTextMatrix(context, CGAffineTransformConcat(trans, runTextMatrix));
  2012. }
  2013. CTRunDraw(run, context, CFRangeMake(0, 0));
  2014. if (!runTextMatrixIsID) {
  2015. CGContextRestoreGState(context);
  2016. }
  2017. } else { // draw glyph
  2018. CTFontRef runFont = CFDictionaryGetValue(runAttrs, kCTFontAttributeName);
  2019. if (!runFont) return;
  2020. NSUInteger glyphCount = CTRunGetGlyphCount(run);
  2021. if (glyphCount <= 0) return;
  2022. CGGlyph glyphs[glyphCount];
  2023. CGPoint glyphPositions[glyphCount];
  2024. CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs);
  2025. CTRunGetPositions(run, CFRangeMake(0, 0), glyphPositions);
  2026. CGColorRef fillColor = (CGColorRef)CFDictionaryGetValue(runAttrs, kCTForegroundColorAttributeName);
  2027. fillColor = YYTextGetCGColor(fillColor);
  2028. NSNumber *strokeWidth = CFDictionaryGetValue(runAttrs, kCTStrokeWidthAttributeName);
  2029. CGContextSaveGState(context); {
  2030. CGContextSetFillColorWithColor(context, fillColor);
  2031. if ((strokeWidth == nil) || strokeWidth.floatValue == 0) {
  2032. CGContextSetTextDrawingMode(context, kCGTextFill);
  2033. } else {
  2034. CGColorRef strokeColor = (CGColorRef)CFDictionaryGetValue(runAttrs, kCTStrokeColorAttributeName);
  2035. if (!strokeColor) strokeColor = fillColor;
  2036. CGContextSetStrokeColorWithColor(context, strokeColor);
  2037. CGContextSetLineWidth(context, CTFontGetSize(runFont) * fabs(strokeWidth.floatValue * 0.01));
  2038. if (strokeWidth.floatValue > 0) {
  2039. CGContextSetTextDrawingMode(context, kCGTextStroke);
  2040. } else {
  2041. CGContextSetTextDrawingMode(context, kCGTextFillStroke);
  2042. }
  2043. }
  2044. if (isVertical) {
  2045. CFIndex runStrIdx[glyphCount + 1];
  2046. CTRunGetStringIndices(run, CFRangeMake(0, 0), runStrIdx);
  2047. CFRange runStrRange = CTRunGetStringRange(run);
  2048. runStrIdx[glyphCount] = runStrRange.location + runStrRange.length;
  2049. CGSize glyphAdvances[glyphCount];
  2050. CTRunGetAdvances(run, CFRangeMake(0, 0), glyphAdvances);
  2051. CGFloat ascent = CTFontGetAscent(runFont);
  2052. CGFloat descent = CTFontGetDescent(runFont);
  2053. CGAffineTransform glyphTransform = glyphTransformValue.CGAffineTransformValue;
  2054. CGPoint zeroPoint = CGPointZero;
  2055. for (YYTextRunGlyphRange *oneRange in runRanges) {
  2056. NSRange range = oneRange.glyphRangeInRun;
  2057. NSUInteger rangeMax = range.location + range.length;
  2058. YYTextRunGlyphDrawMode mode = oneRange.drawMode;
  2059. for (NSUInteger g = range.location; g < rangeMax; g++) {
  2060. CGContextSaveGState(context); {
  2061. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2062. if (glyphTransformValue) {
  2063. CGContextSetTextMatrix(context, glyphTransform);
  2064. }
  2065. if (mode) { // CJK glyph, need rotated
  2066. CGFloat ofs = (ascent - descent) * 0.5;
  2067. CGFloat w = glyphAdvances[g].width * 0.5;
  2068. CGFloat x = x = line.position.x + verticalOffset + glyphPositions[g].y + (ofs - w);
  2069. CGFloat y = -line.position.y + size.height - glyphPositions[g].x - (ofs + w);
  2070. if (mode == YYTextRunGlyphDrawModeVerticalRotateMove) {
  2071. x += w;
  2072. y += w;
  2073. }
  2074. CGContextSetTextPosition(context, x, y);
  2075. } else {
  2076. CGContextRotateCTM(context, DegreesToRadians(-90));
  2077. CGContextSetTextPosition(context,
  2078. line.position.y - size.height + glyphPositions[g].x,
  2079. line.position.x + verticalOffset + glyphPositions[g].y);
  2080. }
  2081. if (CTFontContainsColorBitmapGlyphs(runFont)) {
  2082. CTFontDrawGlyphs(runFont, glyphs + g, &zeroPoint, 1, context);
  2083. } else {
  2084. CGFontRef cgFont = CTFontCopyGraphicsFont(runFont, NULL);
  2085. CGContextSetFont(context, cgFont);
  2086. CGContextSetFontSize(context, CTFontGetSize(runFont));
  2087. CGContextShowGlyphsAtPositions(context, glyphs + g, &zeroPoint, 1);
  2088. CGFontRelease(cgFont);
  2089. }
  2090. } CGContextRestoreGState(context);
  2091. }
  2092. }
  2093. } else { // not vertical
  2094. if (glyphTransformValue) {
  2095. CFIndex runStrIdx[glyphCount + 1];
  2096. CTRunGetStringIndices(run, CFRangeMake(0, 0), runStrIdx);
  2097. CFRange runStrRange = CTRunGetStringRange(run);
  2098. runStrIdx[glyphCount] = runStrRange.location + runStrRange.length;
  2099. CGSize glyphAdvances[glyphCount];
  2100. CTRunGetAdvances(run, CFRangeMake(0, 0), glyphAdvances);
  2101. CGAffineTransform glyphTransform = glyphTransformValue.CGAffineTransformValue;
  2102. CGPoint zeroPoint = CGPointZero;
  2103. for (NSUInteger g = 0; g < glyphCount; g++) {
  2104. CGContextSaveGState(context); {
  2105. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2106. CGContextSetTextMatrix(context, glyphTransform);
  2107. CGContextSetTextPosition(context,
  2108. line.position.x + glyphPositions[g].x,
  2109. size.height - (line.position.y + glyphPositions[g].y));
  2110. if (CTFontContainsColorBitmapGlyphs(runFont)) {
  2111. CTFontDrawGlyphs(runFont, glyphs + g, &zeroPoint, 1, context);
  2112. } else {
  2113. CGFontRef cgFont = CTFontCopyGraphicsFont(runFont, NULL);
  2114. CGContextSetFont(context, cgFont);
  2115. CGContextSetFontSize(context, CTFontGetSize(runFont));
  2116. CGContextShowGlyphsAtPositions(context, glyphs + g, &zeroPoint, 1);
  2117. CGFontRelease(cgFont);
  2118. }
  2119. } CGContextRestoreGState(context);
  2120. }
  2121. } else {
  2122. if (CTFontContainsColorBitmapGlyphs(runFont)) {
  2123. CTFontDrawGlyphs(runFont, glyphs, glyphPositions, glyphCount, context);
  2124. } else {
  2125. CGFontRef cgFont = CTFontCopyGraphicsFont(runFont, NULL);
  2126. CGContextSetFont(context, cgFont);
  2127. CGContextSetFontSize(context, CTFontGetSize(runFont));
  2128. CGContextShowGlyphsAtPositions(context, glyphs, glyphPositions, glyphCount);
  2129. CGFontRelease(cgFont);
  2130. }
  2131. }
  2132. }
  2133. } CGContextRestoreGState(context);
  2134. }
  2135. }
  2136. static void YYTextSetLinePatternInContext(YYTextLineStyle style, CGFloat width, CGFloat phase, CGContextRef context){
  2137. CGContextSetLineWidth(context, width);
  2138. CGContextSetLineCap(context, kCGLineCapButt);
  2139. CGContextSetLineJoin(context, kCGLineJoinMiter);
  2140. CGFloat dash = 12, dot = 5, space = 3;
  2141. NSUInteger pattern = style & 0xF00;
  2142. if (pattern == YYTextLineStylePatternSolid) {
  2143. CGContextSetLineDash(context, phase, NULL, 0);
  2144. } else if (pattern == YYTextLineStylePatternDot) {
  2145. CGFloat lengths[2] = {width * dot, width * space};
  2146. CGContextSetLineDash(context, phase, lengths, 2);
  2147. } else if (pattern == YYTextLineStylePatternDash) {
  2148. CGFloat lengths[2] = {width * dash, width * space};
  2149. CGContextSetLineDash(context, phase, lengths, 2);
  2150. } else if (pattern == YYTextLineStylePatternDashDot) {
  2151. CGFloat lengths[4] = {width * dash, width * space, width * dot, width * space};
  2152. CGContextSetLineDash(context, phase, lengths, 4);
  2153. } else if (pattern == YYTextLineStylePatternDashDotDot) {
  2154. CGFloat lengths[6] = {width * dash, width * space,width * dot, width * space, width * dot, width * space};
  2155. CGContextSetLineDash(context, phase, lengths, 6);
  2156. } else if (pattern == YYTextLineStylePatternCircleDot) {
  2157. CGFloat lengths[2] = {width * 0, width * 3};
  2158. CGContextSetLineDash(context, phase, lengths, 2);
  2159. CGContextSetLineCap(context, kCGLineCapRound);
  2160. CGContextSetLineJoin(context, kCGLineJoinRound);
  2161. }
  2162. }
  2163. static void YYTextDrawBorderRects(CGContextRef context, CGSize size, YYTextBorder *border, NSArray *rects, BOOL isVertical) {
  2164. if (rects.count == 0) return;
  2165. YYTextShadow *shadow = border.shadow;
  2166. if (shadow.color) {
  2167. CGContextSaveGState(context);
  2168. CGContextSetShadowWithColor(context, shadow.offset, shadow.radius, shadow.color.CGColor);
  2169. CGContextBeginTransparencyLayer(context, NULL);
  2170. }
  2171. NSMutableArray *paths = [NSMutableArray new];
  2172. for (NSValue *value in rects) {
  2173. CGRect rect = value.CGRectValue;
  2174. if (isVertical) {
  2175. rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetRotateVertical(border.insets));
  2176. } else {
  2177. rect = UIEdgeInsetsInsetRect(rect, border.insets);
  2178. }
  2179. rect = CGRectPixelRound(rect);
  2180. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:border.cornerRadius];
  2181. [path closePath];
  2182. [paths addObject:path];
  2183. }
  2184. if (border.fillColor) {
  2185. CGContextSaveGState(context);
  2186. CGContextSetFillColorWithColor(context, border.fillColor.CGColor);
  2187. for (UIBezierPath *path in paths) {
  2188. CGContextAddPath(context, path.CGPath);
  2189. }
  2190. CGContextFillPath(context);
  2191. CGContextRestoreGState(context);
  2192. }
  2193. if (border.strokeColor && border.lineStyle > 0 && border.strokeWidth > 0) {
  2194. //-------------------------- single line ------------------------------//
  2195. CGContextSaveGState(context);
  2196. for (UIBezierPath *path in paths) {
  2197. CGRect bounds = CGRectUnion(path.bounds, (CGRect){CGPointZero, size});
  2198. bounds = CGRectInset(bounds, -2 * border.strokeWidth, -2 * border.strokeWidth);
  2199. CGContextAddRect(context, bounds);
  2200. CGContextAddPath(context, path.CGPath);
  2201. CGContextEOClip(context);
  2202. }
  2203. [border.strokeColor setStroke];
  2204. YYTextSetLinePatternInContext(border.lineStyle, border.strokeWidth, 0, context);
  2205. CGFloat inset = -border.strokeWidth * 0.5;
  2206. if ((border.lineStyle & 0xFF) == YYTextLineStyleThick) {
  2207. inset *= 2;
  2208. CGContextSetLineWidth(context, border.strokeWidth * 2);
  2209. }
  2210. CGFloat radiusDelta = -inset;
  2211. if (border.cornerRadius <= 0) {
  2212. radiusDelta = 0;
  2213. }
  2214. CGContextSetLineJoin(context, border.lineJoin);
  2215. for (NSValue *value in rects) {
  2216. CGRect rect = value.CGRectValue;
  2217. if (isVertical) {
  2218. rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetRotateVertical(border.insets));
  2219. } else {
  2220. rect = UIEdgeInsetsInsetRect(rect, border.insets);
  2221. }
  2222. rect = CGRectInset(rect, inset, inset);
  2223. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:border.cornerRadius + radiusDelta];
  2224. [path closePath];
  2225. CGContextAddPath(context, path.CGPath);
  2226. }
  2227. CGContextStrokePath(context);
  2228. CGContextRestoreGState(context);
  2229. //------------------------- second line ------------------------------//
  2230. if ((border.lineStyle & 0xFF) == YYTextLineStyleDouble) {
  2231. CGContextSaveGState(context);
  2232. CGFloat inset = -border.strokeWidth * 2;
  2233. for (NSValue *value in rects) {
  2234. CGRect rect = value.CGRectValue;
  2235. rect = UIEdgeInsetsInsetRect(rect, border.insets);
  2236. rect = CGRectInset(rect, inset, inset);
  2237. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:border.cornerRadius + 2 * border.strokeWidth];
  2238. [path closePath];
  2239. CGRect bounds = CGRectUnion(path.bounds, (CGRect){CGPointZero, size});
  2240. bounds = CGRectInset(bounds, -2 * border.strokeWidth, -2 * border.strokeWidth);
  2241. CGContextAddRect(context, bounds);
  2242. CGContextAddPath(context, path.CGPath);
  2243. CGContextEOClip(context);
  2244. }
  2245. CGContextSetStrokeColorWithColor(context, border.strokeColor.CGColor);
  2246. YYTextSetLinePatternInContext(border.lineStyle, border.strokeWidth, 0, context);
  2247. CGContextSetLineJoin(context, border.lineJoin);
  2248. inset = -border.strokeWidth * 2.5;
  2249. radiusDelta = border.strokeWidth * 2;
  2250. if (border.cornerRadius <= 0) {
  2251. radiusDelta = 0;
  2252. }
  2253. for (NSValue *value in rects) {
  2254. CGRect rect = value.CGRectValue;
  2255. rect = UIEdgeInsetsInsetRect(rect, border.insets);
  2256. rect = CGRectInset(rect, inset, inset);
  2257. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:border.cornerRadius + radiusDelta];
  2258. [path closePath];
  2259. CGContextAddPath(context, path.CGPath);
  2260. }
  2261. CGContextStrokePath(context);
  2262. CGContextRestoreGState(context);
  2263. }
  2264. }
  2265. if (shadow.color) {
  2266. CGContextEndTransparencyLayer(context);
  2267. CGContextRestoreGState(context);
  2268. }
  2269. }
  2270. static void YYTextDrawLineStyle(CGContextRef context, CGFloat length, CGFloat lineWidth, YYTextLineStyle style, CGPoint position, CGColorRef color, BOOL isVertical) {
  2271. NSUInteger styleBase = style & 0xFF;
  2272. if (styleBase == 0) return;
  2273. CGContextSaveGState(context); {
  2274. if (isVertical) {
  2275. CGFloat x, y1, y2, w;
  2276. y1 = CGFloatPixelRound(position.y);
  2277. y2 = CGFloatPixelRound(position.y + length);
  2278. w = (styleBase == YYTextLineStyleThick ? lineWidth * 2 : lineWidth);
  2279. CGFloat linePixel = CGFloatToPixel(w);
  2280. if (fabs(linePixel - floor(linePixel)) < 0.1) {
  2281. int iPixel = linePixel;
  2282. if (iPixel == 0 || (iPixel % 2)) { // odd line pixel
  2283. x = CGFloatPixelHalf(position.x);
  2284. } else {
  2285. x = CGFloatPixelFloor(position.x);
  2286. }
  2287. } else {
  2288. x = position.x;
  2289. }
  2290. CGContextSetStrokeColorWithColor(context, color);
  2291. YYTextSetLinePatternInContext(style, lineWidth, position.y, context);
  2292. CGContextSetLineWidth(context, w);
  2293. if (styleBase == YYTextLineStyleSingle) {
  2294. CGContextMoveToPoint(context, x, y1);
  2295. CGContextAddLineToPoint(context, x, y2);
  2296. CGContextStrokePath(context);
  2297. } else if (styleBase == YYTextLineStyleThick) {
  2298. CGContextMoveToPoint(context, x, y1);
  2299. CGContextAddLineToPoint(context, x, y2);
  2300. CGContextStrokePath(context);
  2301. } else if (styleBase == YYTextLineStyleDouble) {
  2302. CGContextMoveToPoint(context, x - w, y1);
  2303. CGContextAddLineToPoint(context, x - w, y2);
  2304. CGContextStrokePath(context);
  2305. CGContextMoveToPoint(context, x + w, y1);
  2306. CGContextAddLineToPoint(context, x + w, y2);
  2307. CGContextStrokePath(context);
  2308. }
  2309. } else {
  2310. CGFloat x1, x2, y, w;
  2311. x1 = CGFloatPixelRound(position.x);
  2312. x2 = CGFloatPixelRound(position.x + length);
  2313. w = (styleBase == YYTextLineStyleThick ? lineWidth * 2 : lineWidth);
  2314. CGFloat linePixel = CGFloatToPixel(w);
  2315. if (fabs(linePixel - floor(linePixel)) < 0.1) {
  2316. int iPixel = linePixel;
  2317. if (iPixel == 0 || (iPixel % 2)) { // odd line pixel
  2318. y = CGFloatPixelHalf(position.y);
  2319. } else {
  2320. y = CGFloatPixelFloor(position.y);
  2321. }
  2322. } else {
  2323. y = position.y;
  2324. }
  2325. CGContextSetStrokeColorWithColor(context, color);
  2326. YYTextSetLinePatternInContext(style, lineWidth, position.x, context);
  2327. CGContextSetLineWidth(context, w);
  2328. if (styleBase == YYTextLineStyleSingle) {
  2329. CGContextMoveToPoint(context, x1, y);
  2330. CGContextAddLineToPoint(context, x2, y);
  2331. CGContextStrokePath(context);
  2332. } else if (styleBase == YYTextLineStyleThick) {
  2333. CGContextMoveToPoint(context, x1, y);
  2334. CGContextAddLineToPoint(context, x2, y);
  2335. CGContextStrokePath(context);
  2336. } else if (styleBase == YYTextLineStyleDouble) {
  2337. CGContextMoveToPoint(context, x1, y - w);
  2338. CGContextAddLineToPoint(context, x2, y - w);
  2339. CGContextStrokePath(context);
  2340. CGContextMoveToPoint(context, x1, y + w);
  2341. CGContextAddLineToPoint(context, x2, y + w);
  2342. CGContextStrokePath(context);
  2343. }
  2344. }
  2345. } CGContextRestoreGState(context);
  2346. }
  2347. static void YYTextDrawText(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, BOOL (^cancel)(void)) {
  2348. CGContextSaveGState(context); {
  2349. CGContextTranslateCTM(context, point.x, point.y);
  2350. CGContextTranslateCTM(context, 0, size.height);
  2351. CGContextScaleCTM(context, 1, -1);
  2352. BOOL isVertical = layout.container.verticalForm;
  2353. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2354. NSArray *lines = layout.lines;
  2355. for (NSUInteger l = 0, lMax = lines.count; l < lMax; l++) {
  2356. YYTextLine *line = lines[l];
  2357. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2358. NSArray *lineRunRanges = line.verticalRotateRange;
  2359. CGFloat posX = line.position.x + verticalOffset;
  2360. CGFloat posY = size.height - line.position.y;
  2361. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2362. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2363. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2364. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2365. CGContextSetTextPosition(context, posX, posY);
  2366. YYTextDrawRun(line, run, context, size, isVertical, lineRunRanges[r], verticalOffset);
  2367. }
  2368. if (cancel && cancel()) break;
  2369. }
  2370. // Use this to draw frame for test/debug.
  2371. // CGContextTranslateCTM(context, verticalOffset, size.height);
  2372. // CTFrameDraw(layout.frame, context);
  2373. } CGContextRestoreGState(context);
  2374. }
  2375. static void YYTextDrawBlockBorder(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, BOOL (^cancel)(void)) {
  2376. CGContextSaveGState(context);
  2377. CGContextTranslateCTM(context, point.x, point.y);
  2378. BOOL isVertical = layout.container.verticalForm;
  2379. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2380. NSArray *lines = layout.lines;
  2381. for (NSInteger l = 0, lMax = lines.count; l < lMax; l++) {
  2382. if (cancel && cancel()) break;
  2383. YYTextLine *line = lines[l];
  2384. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2385. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2386. for (NSInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2387. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2388. CFIndex glyphCount = CTRunGetGlyphCount(run);
  2389. if (glyphCount == 0) continue;
  2390. NSDictionary *attrs = (id)CTRunGetAttributes(run);
  2391. YYTextBorder *border = attrs[YYTextBlockBorderAttributeName];
  2392. if (!border) continue;
  2393. NSUInteger lineStartIndex = line.index;
  2394. while (lineStartIndex > 0) {
  2395. if (((YYTextLine *)lines[lineStartIndex - 1]).row == line.row) lineStartIndex--;
  2396. else break;
  2397. }
  2398. CGRect unionRect = CGRectZero;
  2399. NSUInteger lineStartRow = ((YYTextLine *)lines[lineStartIndex]).row;
  2400. NSUInteger lineContinueIndex = lineStartIndex;
  2401. NSUInteger lineContinueRow = lineStartRow;
  2402. do {
  2403. YYTextLine *one = lines[lineContinueIndex];
  2404. if (lineContinueIndex == lineStartIndex) {
  2405. unionRect = one.bounds;
  2406. } else {
  2407. unionRect = CGRectUnion(unionRect, one.bounds);
  2408. }
  2409. if (lineContinueIndex + 1 == lMax) break;
  2410. YYTextLine *next = lines[lineContinueIndex + 1];
  2411. if (next.row != lineContinueRow) {
  2412. YYTextBorder *nextBorder = [layout.text attribute:YYTextBlockBorderAttributeName atIndex:next.range.location];
  2413. if ([nextBorder isEqual:border]) {
  2414. lineContinueRow++;
  2415. } else {
  2416. break;
  2417. }
  2418. }
  2419. lineContinueIndex++;
  2420. } while (true);
  2421. if (isVertical) {
  2422. UIEdgeInsets insets = layout.container.insets;
  2423. unionRect.origin.y = insets.top;
  2424. unionRect.size.height = layout.container.size.height -insets.top - insets.bottom;
  2425. } else {
  2426. UIEdgeInsets insets = layout.container.insets;
  2427. unionRect.origin.x = insets.left;
  2428. unionRect.size.width = layout.container.size.width -insets.left - insets.right;
  2429. }
  2430. unionRect.origin.x += verticalOffset;
  2431. YYTextDrawBorderRects(context, size, border, @[[NSValue valueWithCGRect:unionRect]], isVertical);
  2432. l = lineContinueIndex;
  2433. break;
  2434. }
  2435. }
  2436. CGContextRestoreGState(context);
  2437. }
  2438. static void YYTextDrawBorder(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, YYTextBorderType type, BOOL (^cancel)(void)) {
  2439. CGContextSaveGState(context);
  2440. CGContextTranslateCTM(context, point.x, point.y);
  2441. BOOL isVertical = layout.container.verticalForm;
  2442. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2443. NSArray *lines = layout.lines;
  2444. NSString *borderKey = (type == YYTextBorderTypeNormal ? YYTextBorderAttributeName : YYTextBackgroundBorderAttributeName);
  2445. BOOL needJumpRun = NO;
  2446. NSUInteger jumpRunIndex = 0;
  2447. for (NSInteger l = 0, lMax = lines.count; l < lMax; l++) {
  2448. if (cancel && cancel()) break;
  2449. YYTextLine *line = lines[l];
  2450. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2451. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2452. for (NSInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2453. if (needJumpRun) {
  2454. needJumpRun = NO;
  2455. r = jumpRunIndex + 1;
  2456. if (r >= rMax) break;
  2457. }
  2458. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2459. CFIndex glyphCount = CTRunGetGlyphCount(run);
  2460. if (glyphCount == 0) continue;
  2461. NSDictionary *attrs = (id)CTRunGetAttributes(run);
  2462. YYTextBorder *border = attrs[borderKey];
  2463. if (!border) continue;
  2464. CFRange runRange = CTRunGetStringRange(run);
  2465. if (runRange.location == kCFNotFound || runRange.length == 0) continue;
  2466. if (runRange.location + runRange.length > layout.text.length) continue;
  2467. NSMutableArray *runRects = [NSMutableArray new];
  2468. NSInteger endLineIndex = l;
  2469. NSInteger endRunIndex = r;
  2470. BOOL endFound = NO;
  2471. for (NSInteger ll = l; ll < lMax; ll++) {
  2472. if (endFound) break;
  2473. YYTextLine *iLine = lines[ll];
  2474. CFArrayRef iRuns = CTLineGetGlyphRuns(iLine.CTLine);
  2475. CGRect extLineRect = CGRectNull;
  2476. for (NSInteger rr = (ll == l) ? r : 0, rrMax = CFArrayGetCount(iRuns); rr < rrMax; rr++) {
  2477. CTRunRef iRun = CFArrayGetValueAtIndex(iRuns, rr);
  2478. NSDictionary *iAttrs = (id)CTRunGetAttributes(iRun);
  2479. YYTextBorder *iBorder = iAttrs[borderKey];
  2480. if (![border isEqual:iBorder]) {
  2481. endFound = YES;
  2482. break;
  2483. }
  2484. endLineIndex = ll;
  2485. endRunIndex = rr;
  2486. CGPoint iRunPosition = CGPointZero;
  2487. CTRunGetPositions(iRun, CFRangeMake(0, 1), &iRunPosition);
  2488. CGFloat ascent, descent;
  2489. CGFloat iRunWidth = CTRunGetTypographicBounds(iRun, CFRangeMake(0, 0), &ascent, &descent, NULL);
  2490. if (isVertical) {
  2491. YY_SWAP(iRunPosition.x, iRunPosition.y);
  2492. iRunPosition.y += iLine.position.y;
  2493. CGRect iRect = CGRectMake(verticalOffset + line.position.x - descent, iRunPosition.y, ascent + descent, iRunWidth);
  2494. if (CGRectIsNull(extLineRect)) {
  2495. extLineRect = iRect;
  2496. } else {
  2497. extLineRect = CGRectUnion(extLineRect, iRect);
  2498. }
  2499. } else {
  2500. iRunPosition.x += iLine.position.x;
  2501. CGRect iRect = CGRectMake(iRunPosition.x, iLine.position.y - ascent, iRunWidth, ascent + descent);
  2502. if (CGRectIsNull(extLineRect)) {
  2503. extLineRect = iRect;
  2504. } else {
  2505. extLineRect = CGRectUnion(extLineRect, iRect);
  2506. }
  2507. }
  2508. }
  2509. if (!CGRectIsNull(extLineRect)) {
  2510. [runRects addObject:[NSValue valueWithCGRect:extLineRect]];
  2511. }
  2512. }
  2513. NSMutableArray *drawRects = [NSMutableArray new];
  2514. CGRect curRect= ((NSValue *)[runRects firstObject]).CGRectValue;
  2515. for (NSInteger re = 0, reMax = runRects.count; re < reMax; re++) {
  2516. CGRect rect = ((NSValue *)runRects[re]).CGRectValue;
  2517. if (isVertical) {
  2518. if (fabs(rect.origin.x - curRect.origin.x) < 1) {
  2519. curRect = YYTextMergeRectInSameLine(rect, curRect, isVertical);
  2520. } else {
  2521. [drawRects addObject:[NSValue valueWithCGRect:curRect]];
  2522. curRect = rect;
  2523. }
  2524. } else {
  2525. if (fabs(rect.origin.y - curRect.origin.y) < 1) {
  2526. curRect = YYTextMergeRectInSameLine(rect, curRect, isVertical);
  2527. } else {
  2528. [drawRects addObject:[NSValue valueWithCGRect:curRect]];
  2529. curRect = rect;
  2530. }
  2531. }
  2532. }
  2533. if (!CGRectEqualToRect(curRect, CGRectZero)) {
  2534. [drawRects addObject:[NSValue valueWithCGRect:curRect]];
  2535. }
  2536. YYTextDrawBorderRects(context, size, border, drawRects, isVertical);
  2537. if (l == endLineIndex) {
  2538. r = endRunIndex;
  2539. } else {
  2540. l = endLineIndex - 1;
  2541. needJumpRun = YES;
  2542. jumpRunIndex = endRunIndex;
  2543. break;
  2544. }
  2545. }
  2546. }
  2547. CGContextRestoreGState(context);
  2548. }
  2549. static void YYTextDrawDecoration(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, YYTextDecorationType type, BOOL (^cancel)(void)) {
  2550. NSArray *lines = layout.lines;
  2551. CGContextSaveGState(context);
  2552. CGContextTranslateCTM(context, point.x, point.y);
  2553. BOOL isVertical = layout.container.verticalForm;
  2554. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2555. CGContextTranslateCTM(context, verticalOffset, 0);
  2556. for (NSUInteger l = 0, lMax = layout.lines.count; l < lMax; l++) {
  2557. if (cancel && cancel()) break;
  2558. YYTextLine *line = lines[l];
  2559. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2560. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2561. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2562. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2563. CFIndex glyphCount = CTRunGetGlyphCount(run);
  2564. if (glyphCount == 0) continue;
  2565. NSDictionary *attrs = (id)CTRunGetAttributes(run);
  2566. YYTextDecoration *underline = attrs[YYTextUnderlineAttributeName];
  2567. YYTextDecoration *strikethrough = attrs[YYTextStrikethroughAttributeName];
  2568. BOOL needDrawUnderline = NO, needDrawStrikethrough = NO;
  2569. if ((type & YYTextDecorationTypeUnderline) && underline.style > 0) {
  2570. needDrawUnderline = YES;
  2571. }
  2572. if ((type & YYTextDecorationTypeStrikethrough) && strikethrough.style > 0) {
  2573. needDrawStrikethrough = YES;
  2574. }
  2575. if (!needDrawUnderline && !needDrawStrikethrough) continue;
  2576. CFRange runRange = CTRunGetStringRange(run);
  2577. if (runRange.location == kCFNotFound || runRange.length == 0) continue;
  2578. if (runRange.location + runRange.length > layout.text.length) continue;
  2579. NSString *runStr = [layout.text attributedSubstringFromRange:NSMakeRange(runRange.location, runRange.length)].string;
  2580. if (YYTextIsLinebreakString(runStr)) continue; // may need more checks...
  2581. CGFloat xHeight, underlinePosition, lineThickness;
  2582. YYTextGetRunsMaxMetric(runs, &xHeight, &underlinePosition, &lineThickness);
  2583. CGPoint underlineStart, strikethroughStart;
  2584. CGFloat length;
  2585. if (isVertical) {
  2586. underlineStart.x = line.position.x + underlinePosition;
  2587. strikethroughStart.x = line.position.x + xHeight / 2;
  2588. CGPoint runPosition = CGPointZero;
  2589. CTRunGetPositions(run, CFRangeMake(0, 1), &runPosition);
  2590. underlineStart.y = strikethroughStart.y = runPosition.x + line.position.y;
  2591. length = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
  2592. } else {
  2593. underlineStart.y = line.position.y - underlinePosition;
  2594. strikethroughStart.y = line.position.y - xHeight / 2;
  2595. CGPoint runPosition = CGPointZero;
  2596. CTRunGetPositions(run, CFRangeMake(0, 1), &runPosition);
  2597. underlineStart.x = strikethroughStart.x = runPosition.x + line.position.x;
  2598. length = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
  2599. }
  2600. if (needDrawUnderline) {
  2601. CGColorRef color = underline.color.CGColor;
  2602. if (!color) {
  2603. color = (__bridge CGColorRef)(attrs[(id)kCTForegroundColorAttributeName]);
  2604. color = YYTextGetCGColor(color);
  2605. }
  2606. CGFloat thickness = (underline.width != nil) ? underline.width.floatValue : lineThickness;
  2607. YYTextShadow *shadow = underline.shadow;
  2608. while (shadow) {
  2609. if (!shadow.color) {
  2610. shadow = shadow.subShadow;
  2611. continue;
  2612. }
  2613. CGFloat offsetAlterX = size.width + 0xFFFF;
  2614. CGContextSaveGState(context); {
  2615. CGSize offset = shadow.offset;
  2616. offset.width -= offsetAlterX;
  2617. CGContextSaveGState(context); {
  2618. CGContextSetShadowWithColor(context, offset, shadow.radius, shadow.color.CGColor);
  2619. CGContextSetBlendMode(context, shadow.blendMode);
  2620. CGContextTranslateCTM(context, offsetAlterX, 0);
  2621. YYTextDrawLineStyle(context, length, thickness, underline.style, underlineStart, color, isVertical);
  2622. } CGContextRestoreGState(context);
  2623. } CGContextRestoreGState(context);
  2624. shadow = shadow.subShadow;
  2625. }
  2626. YYTextDrawLineStyle(context, length, thickness, underline.style, underlineStart, color, isVertical);
  2627. }
  2628. if (needDrawStrikethrough) {
  2629. CGColorRef color = strikethrough.color.CGColor;
  2630. if (!color) {
  2631. color = (__bridge CGColorRef)(attrs[(id)kCTForegroundColorAttributeName]);
  2632. color = YYTextGetCGColor(color);
  2633. }
  2634. CGFloat thickness = (strikethrough.width != nil) ? strikethrough.width.floatValue : lineThickness;
  2635. YYTextShadow *shadow = underline.shadow;
  2636. while (shadow) {
  2637. if (!shadow.color) {
  2638. shadow = shadow.subShadow;
  2639. continue;
  2640. }
  2641. CGFloat offsetAlterX = size.width + 0xFFFF;
  2642. CGContextSaveGState(context); {
  2643. CGSize offset = shadow.offset;
  2644. offset.width -= offsetAlterX;
  2645. CGContextSaveGState(context); {
  2646. CGContextSetShadowWithColor(context, offset, shadow.radius, shadow.color.CGColor);
  2647. CGContextSetBlendMode(context, shadow.blendMode);
  2648. CGContextTranslateCTM(context, offsetAlterX, 0);
  2649. YYTextDrawLineStyle(context, length, thickness, underline.style, underlineStart, color, isVertical);
  2650. } CGContextRestoreGState(context);
  2651. } CGContextRestoreGState(context);
  2652. shadow = shadow.subShadow;
  2653. }
  2654. YYTextDrawLineStyle(context, length, thickness, strikethrough.style, strikethroughStart, color, isVertical);
  2655. }
  2656. }
  2657. }
  2658. CGContextRestoreGState(context);
  2659. }
  2660. static void YYTextDrawAttachment(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, UIView *targetView, CALayer *targetLayer, BOOL (^cancel)(void)) {
  2661. BOOL isVertical = layout.container.verticalForm;
  2662. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2663. for (NSUInteger i = 0, max = layout.attachments.count; i < max; i++) {
  2664. YYTextAttachment *a = layout.attachments[i];
  2665. if (!a.content) continue;
  2666. UIImage *image = nil;
  2667. UIView *view = nil;
  2668. CALayer *layer = nil;
  2669. if ([a.content isKindOfClass:[UIImage class]]) {
  2670. image = a.content;
  2671. } else if ([a.content isKindOfClass:[UIView class]]) {
  2672. view = a.content;
  2673. } else if ([a.content isKindOfClass:[CALayer class]]) {
  2674. layer = a.content;
  2675. }
  2676. if (!image && !view && !layer) continue;
  2677. if (image && !context) continue;
  2678. if (view && !targetView) continue;
  2679. if (layer && !targetLayer) continue;
  2680. if (cancel && cancel()) break;
  2681. CGSize asize = image ? image.size : view ? view.frame.size : layer.frame.size;
  2682. CGRect rect = ((NSValue *)layout.attachmentRects[i]).CGRectValue;
  2683. if (isVertical) {
  2684. rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetRotateVertical(a.contentInsets));
  2685. } else {
  2686. rect = UIEdgeInsetsInsetRect(rect, a.contentInsets);
  2687. }
  2688. rect = YYCGRectFitWithContentMode(rect, asize, a.contentMode);
  2689. rect = CGRectPixelRound(rect);
  2690. rect = CGRectStandardize(rect);
  2691. rect.origin.x += point.x + verticalOffset;
  2692. rect.origin.y += point.y;
  2693. if (image) {
  2694. CGImageRef ref = image.CGImage;
  2695. if (ref) {
  2696. CGContextSaveGState(context);
  2697. CGContextTranslateCTM(context, 0, CGRectGetMaxY(rect) + CGRectGetMinY(rect));
  2698. CGContextScaleCTM(context, 1, -1);
  2699. CGContextDrawImage(context, rect, ref);
  2700. CGContextRestoreGState(context);
  2701. }
  2702. } else if (view) {
  2703. view.frame = rect;
  2704. [targetView addSubview:view];
  2705. } else if (layer) {
  2706. layer.frame = rect;
  2707. [targetLayer addSublayer:layer];
  2708. }
  2709. }
  2710. }
  2711. static void YYTextDrawShadow(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, BOOL (^cancel)(void)) {
  2712. //move out of context. (0xFFFF is just a random large number)
  2713. CGFloat offsetAlterX = size.width + 0xFFFF;
  2714. BOOL isVertical = layout.container.verticalForm;
  2715. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2716. CGContextSaveGState(context); {
  2717. CGContextTranslateCTM(context, point.x, point.y);
  2718. CGContextTranslateCTM(context, 0, size.height);
  2719. CGContextScaleCTM(context, 1, -1);
  2720. NSArray *lines = layout.lines;
  2721. for (NSUInteger l = 0, lMax = layout.lines.count; l < lMax; l++) {
  2722. if (cancel && cancel()) break;
  2723. YYTextLine *line = lines[l];
  2724. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2725. NSArray *lineRunRanges = line.verticalRotateRange;
  2726. CGFloat linePosX = line.position.x;
  2727. CGFloat linePosY = size.height - line.position.y;
  2728. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2729. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2730. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2731. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2732. CGContextSetTextPosition(context, linePosX, linePosY);
  2733. NSDictionary *attrs = (id)CTRunGetAttributes(run);
  2734. YYTextShadow *shadow = attrs[YYTextShadowAttributeName];
  2735. YYTextShadow *nsShadow = [YYTextShadow shadowWithNSShadow:attrs[NSShadowAttributeName]]; // NSShadow compatible
  2736. if (nsShadow) {
  2737. nsShadow.subShadow = shadow;
  2738. shadow = nsShadow;
  2739. }
  2740. while (shadow) {
  2741. if (!shadow.color) {
  2742. shadow = shadow.subShadow;
  2743. continue;
  2744. }
  2745. CGSize offset = shadow.offset;
  2746. offset.width -= offsetAlterX;
  2747. CGContextSaveGState(context); {
  2748. CGContextSetShadowWithColor(context, offset, shadow.radius, shadow.color.CGColor);
  2749. CGContextSetBlendMode(context, shadow.blendMode);
  2750. CGContextTranslateCTM(context, offsetAlterX, 0);
  2751. YYTextDrawRun(line, run, context, size, isVertical, lineRunRanges[r], verticalOffset);
  2752. } CGContextRestoreGState(context);
  2753. shadow = shadow.subShadow;
  2754. }
  2755. }
  2756. }
  2757. } CGContextRestoreGState(context);
  2758. }
  2759. static void YYTextDrawInnerShadow(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, BOOL (^cancel)(void)) {
  2760. CGContextSaveGState(context);
  2761. CGContextTranslateCTM(context, point.x, point.y);
  2762. CGContextTranslateCTM(context, 0, size.height);
  2763. CGContextScaleCTM(context, 1, -1);
  2764. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2765. BOOL isVertical = layout.container.verticalForm;
  2766. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2767. NSArray *lines = layout.lines;
  2768. for (NSUInteger l = 0, lMax = lines.count; l < lMax; l++) {
  2769. if (cancel && cancel()) break;
  2770. YYTextLine *line = lines[l];
  2771. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2772. NSArray *lineRunRanges = line.verticalRotateRange;
  2773. CGFloat linePosX = line.position.x;
  2774. CGFloat linePosY = size.height - line.position.y;
  2775. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2776. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2777. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2778. if (CTRunGetGlyphCount(run) == 0) continue;
  2779. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  2780. CGContextSetTextPosition(context, linePosX, linePosY);
  2781. NSDictionary *attrs = (id)CTRunGetAttributes(run);
  2782. YYTextShadow *shadow = attrs[YYTextInnerShadowAttributeName];
  2783. while (shadow) {
  2784. if (!shadow.color) {
  2785. shadow = shadow.subShadow;
  2786. continue;
  2787. }
  2788. CGPoint runPosition = CGPointZero;
  2789. CTRunGetPositions(run, CFRangeMake(0, 1), &runPosition);
  2790. CGRect runImageBounds = CTRunGetImageBounds(run, context, CFRangeMake(0, 0));
  2791. runImageBounds.origin.x += runPosition.x;
  2792. if (runImageBounds.size.width < 0.1 || runImageBounds.size.height < 0.1) continue;
  2793. CFDictionaryRef runAttrs = CTRunGetAttributes(run);
  2794. NSValue *glyphTransformValue = CFDictionaryGetValue(runAttrs, (__bridge const void *)(YYTextGlyphTransformAttributeName));
  2795. if (glyphTransformValue) {
  2796. runImageBounds = CGRectMake(0, 0, size.width, size.height);
  2797. }
  2798. // text inner shadow
  2799. CGContextSaveGState(context); {
  2800. CGContextSetBlendMode(context, shadow.blendMode);
  2801. CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL);
  2802. CGContextSetAlpha(context, CGColorGetAlpha(shadow.color.CGColor));
  2803. CGContextClipToRect(context, runImageBounds);
  2804. CGContextBeginTransparencyLayer(context, NULL); {
  2805. UIColor *opaqueShadowColor = [shadow.color colorWithAlphaComponent:1];
  2806. CGContextSetShadowWithColor(context, shadow.offset, shadow.radius, opaqueShadowColor.CGColor);
  2807. CGContextSetFillColorWithColor(context, opaqueShadowColor.CGColor);
  2808. CGContextSetBlendMode(context, kCGBlendModeSourceOut);
  2809. CGContextBeginTransparencyLayer(context, NULL); {
  2810. CGContextFillRect(context, runImageBounds);
  2811. CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
  2812. CGContextBeginTransparencyLayer(context, NULL); {
  2813. YYTextDrawRun(line, run, context, size, isVertical, lineRunRanges[r], verticalOffset);
  2814. } CGContextEndTransparencyLayer(context);
  2815. } CGContextEndTransparencyLayer(context);
  2816. } CGContextEndTransparencyLayer(context);
  2817. } CGContextRestoreGState(context);
  2818. shadow = shadow.subShadow;
  2819. }
  2820. }
  2821. }
  2822. CGContextRestoreGState(context);
  2823. }
  2824. static void YYTextDrawDebug(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, YYTextDebugOption *op) {
  2825. UIGraphicsPushContext(context);
  2826. CGContextSaveGState(context);
  2827. CGContextTranslateCTM(context, point.x, point.y);
  2828. CGContextSetLineWidth(context, 1.0 / YYScreenScale());
  2829. CGContextSetLineDash(context, 0, NULL, 0);
  2830. CGContextSetLineJoin(context, kCGLineJoinMiter);
  2831. CGContextSetLineCap(context, kCGLineCapButt);
  2832. BOOL isVertical = layout.container.verticalForm;
  2833. CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
  2834. CGContextTranslateCTM(context, verticalOffset, 0);
  2835. if (op.CTFrameBorderColor || op.CTFrameFillColor) {
  2836. UIBezierPath *path = layout.container.path;
  2837. if (!path) {
  2838. CGRect rect = (CGRect){CGPointZero, layout.container.size};
  2839. rect = UIEdgeInsetsInsetRect(rect, layout.container.insets);
  2840. if (op.CTFrameBorderColor) rect = CGRectPixelHalf(rect);
  2841. else rect = CGRectPixelRound(rect);
  2842. path = [UIBezierPath bezierPathWithRect:rect];
  2843. }
  2844. [path closePath];
  2845. for (UIBezierPath *ex in layout.container.exclusionPaths) {
  2846. [path appendPath:ex];
  2847. }
  2848. if (op.CTFrameFillColor) {
  2849. [op.CTFrameFillColor setFill];
  2850. if (layout.container.pathLineWidth > 0) {
  2851. CGContextSaveGState(context); {
  2852. CGContextBeginTransparencyLayer(context, NULL); {
  2853. CGContextAddPath(context, path.CGPath);
  2854. if (layout.container.pathFillEvenOdd) {
  2855. CGContextEOFillPath(context);
  2856. } else {
  2857. CGContextFillPath(context);
  2858. }
  2859. CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
  2860. [[UIColor blackColor] setFill];
  2861. CGPathRef cgPath = CGPathCreateCopyByStrokingPath(path.CGPath, NULL, layout.container.pathLineWidth, kCGLineCapButt, kCGLineJoinMiter, 0);
  2862. if (cgPath) {
  2863. CGContextAddPath(context, cgPath);
  2864. CGContextFillPath(context);
  2865. }
  2866. CGPathRelease(cgPath);
  2867. } CGContextEndTransparencyLayer(context);
  2868. } CGContextRestoreGState(context);
  2869. } else {
  2870. CGContextAddPath(context, path.CGPath);
  2871. if (layout.container.pathFillEvenOdd) {
  2872. CGContextEOFillPath(context);
  2873. } else {
  2874. CGContextFillPath(context);
  2875. }
  2876. }
  2877. }
  2878. if (op.CTFrameBorderColor) {
  2879. CGContextSaveGState(context); {
  2880. if (layout.container.pathLineWidth > 0) {
  2881. CGContextSetLineWidth(context, layout.container.pathLineWidth);
  2882. }
  2883. [op.CTFrameBorderColor setStroke];
  2884. CGContextAddPath(context, path.CGPath);
  2885. CGContextStrokePath(context);
  2886. } CGContextRestoreGState(context);
  2887. }
  2888. }
  2889. NSArray *lines = layout.lines;
  2890. for (NSUInteger l = 0, lMax = lines.count; l < lMax; l++) {
  2891. YYTextLine *line = lines[l];
  2892. if (layout.truncatedLine && layout.truncatedLine.index == line.index) line = layout.truncatedLine;
  2893. CGRect lineBounds = line.bounds;
  2894. if (op.CTLineFillColor) {
  2895. [op.CTLineFillColor setFill];
  2896. CGContextAddRect(context, CGRectPixelRound(lineBounds));
  2897. CGContextFillPath(context);
  2898. }
  2899. if (op.CTLineBorderColor) {
  2900. [op.CTLineBorderColor setStroke];
  2901. CGContextAddRect(context, CGRectPixelHalf(lineBounds));
  2902. CGContextStrokePath(context);
  2903. }
  2904. if (op.baselineColor) {
  2905. [op.baselineColor setStroke];
  2906. if (isVertical) {
  2907. CGFloat x = CGFloatPixelHalf(line.position.x);
  2908. CGFloat y1 = CGFloatPixelHalf(line.top);
  2909. CGFloat y2 = CGFloatPixelHalf(line.bottom);
  2910. CGContextMoveToPoint(context, x, y1);
  2911. CGContextAddLineToPoint(context, x, y2);
  2912. CGContextStrokePath(context);
  2913. } else {
  2914. CGFloat x1 = CGFloatPixelHalf(lineBounds.origin.x);
  2915. CGFloat x2 = CGFloatPixelHalf(lineBounds.origin.x + lineBounds.size.width);
  2916. CGFloat y = CGFloatPixelHalf(line.position.y);
  2917. CGContextMoveToPoint(context, x1, y);
  2918. CGContextAddLineToPoint(context, x2, y);
  2919. CGContextStrokePath(context);
  2920. }
  2921. }
  2922. if (op.CTLineNumberColor) {
  2923. [op.CTLineNumberColor set];
  2924. NSMutableAttributedString *num = [[NSMutableAttributedString alloc] initWithString:@(l).description];
  2925. num.color = op.CTLineNumberColor;
  2926. num.font = [UIFont systemFontOfSize:6];
  2927. [num drawAtPoint:CGPointMake(line.position.x, line.position.y - (isVertical ? 1 : 6))];
  2928. }
  2929. if (op.CTRunFillColor || op.CTRunBorderColor || op.CTRunNumberColor || op.CGGlyphFillColor || op.CGGlyphBorderColor) {
  2930. CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
  2931. for (NSUInteger r = 0, rMax = CFArrayGetCount(runs); r < rMax; r++) {
  2932. CTRunRef run = CFArrayGetValueAtIndex(runs, r);
  2933. CFIndex glyphCount = CTRunGetGlyphCount(run);
  2934. if (glyphCount == 0) continue;
  2935. CGPoint glyphPositions[glyphCount];
  2936. CTRunGetPositions(run, CFRangeMake(0, glyphCount), glyphPositions);
  2937. CGSize glyphAdvances[glyphCount];
  2938. CTRunGetAdvances(run, CFRangeMake(0, glyphCount), glyphAdvances);
  2939. CGPoint runPosition = glyphPositions[0];
  2940. if (isVertical) {
  2941. YY_SWAP(runPosition.x, runPosition.y);
  2942. runPosition.x = line.position.x;
  2943. runPosition.y += line.position.y;
  2944. } else {
  2945. runPosition.x += line.position.x;
  2946. runPosition.y = line.position.y - runPosition.y;
  2947. }
  2948. CGFloat ascent, descent, leading;
  2949. CGFloat width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, &leading);
  2950. CGRect runTypoBounds;
  2951. if (isVertical) {
  2952. runTypoBounds = CGRectMake(runPosition.x - descent, runPosition.y, ascent + descent, width);
  2953. } else {
  2954. runTypoBounds = CGRectMake(runPosition.x, line.position.y - ascent, width, ascent + descent);
  2955. }
  2956. if (op.CTRunFillColor) {
  2957. [op.CTRunFillColor setFill];
  2958. CGContextAddRect(context, CGRectPixelRound(runTypoBounds));
  2959. CGContextFillPath(context);
  2960. }
  2961. if (op.CTRunBorderColor) {
  2962. [op.CTRunBorderColor setStroke];
  2963. CGContextAddRect(context, CGRectPixelHalf(runTypoBounds));
  2964. CGContextStrokePath(context);
  2965. }
  2966. if (op.CTRunNumberColor) {
  2967. [op.CTRunNumberColor set];
  2968. NSMutableAttributedString *num = [[NSMutableAttributedString alloc] initWithString:@(r).description];
  2969. num.color = op.CTRunNumberColor;
  2970. num.font = [UIFont systemFontOfSize:6];
  2971. [num drawAtPoint:CGPointMake(runTypoBounds.origin.x, runTypoBounds.origin.y - 1)];
  2972. }
  2973. if (op.CGGlyphBorderColor || op.CGGlyphFillColor) {
  2974. for (NSUInteger g = 0; g < glyphCount; g++) {
  2975. CGPoint pos = glyphPositions[g];
  2976. CGSize adv = glyphAdvances[g];
  2977. CGRect rect;
  2978. if (isVertical) {
  2979. YY_SWAP(pos.x, pos.y);
  2980. pos.x = runPosition.x;
  2981. pos.y += line.position.y;
  2982. rect = CGRectMake(pos.x - descent, pos.y, runTypoBounds.size.width, adv.width);
  2983. } else {
  2984. pos.x += line.position.x;
  2985. pos.y = runPosition.y;
  2986. rect = CGRectMake(pos.x, pos.y - ascent, adv.width, runTypoBounds.size.height);
  2987. }
  2988. if (op.CGGlyphFillColor) {
  2989. [op.CGGlyphFillColor setFill];
  2990. CGContextAddRect(context, CGRectPixelRound(rect));
  2991. CGContextFillPath(context);
  2992. }
  2993. if (op.CGGlyphBorderColor) {
  2994. [op.CGGlyphBorderColor setStroke];
  2995. CGContextAddRect(context, CGRectPixelHalf(rect));
  2996. CGContextStrokePath(context);
  2997. }
  2998. }
  2999. }
  3000. }
  3001. }
  3002. }
  3003. CGContextRestoreGState(context);
  3004. UIGraphicsPopContext();
  3005. }
  3006. - (void)drawInContext:(CGContextRef)context
  3007. size:(CGSize)size
  3008. point:(CGPoint)point
  3009. view:(UIView *)view
  3010. layer:(CALayer *)layer
  3011. debug:(YYTextDebugOption *)debug
  3012. cancel:(BOOL (^)(void))cancel{
  3013. @autoreleasepool {
  3014. if (self.needDrawBlockBorder && context) {
  3015. if (cancel && cancel()) return;
  3016. YYTextDrawBlockBorder(self, context, size, point, cancel);
  3017. }
  3018. if (self.needDrawBackgroundBorder && context) {
  3019. if (cancel && cancel()) return;
  3020. YYTextDrawBorder(self, context, size, point, YYTextBorderTypeBackgound, cancel);
  3021. }
  3022. if (self.needDrawShadow && context) {
  3023. if (cancel && cancel()) return;
  3024. YYTextDrawShadow(self, context, size, point, cancel);
  3025. }
  3026. if (self.needDrawUnderline && context) {
  3027. if (cancel && cancel()) return;
  3028. YYTextDrawDecoration(self, context, size, point, YYTextDecorationTypeUnderline, cancel);
  3029. }
  3030. if (self.needDrawText && context) {
  3031. if (cancel && cancel()) return;
  3032. YYTextDrawText(self, context, size, point, cancel);
  3033. }
  3034. if (self.needDrawAttachment && (context || view || layer)) {
  3035. if (cancel && cancel()) return;
  3036. YYTextDrawAttachment(self, context, size, point, view, layer, cancel);
  3037. }
  3038. if (self.needDrawInnerShadow && context) {
  3039. if (cancel && cancel()) return;
  3040. YYTextDrawInnerShadow(self, context, size, point, cancel);
  3041. }
  3042. if (self.needDrawStrikethrough && context) {
  3043. if (cancel && cancel()) return;
  3044. YYTextDrawDecoration(self, context, size, point, YYTextDecorationTypeStrikethrough, cancel);
  3045. }
  3046. if (self.needDrawBorder && context) {
  3047. if (cancel && cancel()) return;
  3048. YYTextDrawBorder(self, context, size, point, YYTextBorderTypeNormal, cancel);
  3049. }
  3050. if (debug.needDrawDebug && context) {
  3051. if (cancel && cancel()) return;
  3052. YYTextDrawDebug(self, context, size, point, debug);
  3053. }
  3054. }
  3055. }
  3056. - (void)drawInContext:(CGContextRef)context
  3057. size:(CGSize)size
  3058. debug:(YYTextDebugOption *)debug {
  3059. [self drawInContext:context size:size point:CGPointZero view:nil layer:nil debug:debug cancel:nil];
  3060. }
  3061. - (void)addAttachmentToView:(UIView *)view layer:(CALayer *)layer {
  3062. YYAssertMainThread();
  3063. [self drawInContext:NULL size:CGSizeZero point:CGPointZero view:view layer:layer debug:nil cancel:nil];
  3064. }
  3065. - (void)removeAttachmentFromViewAndLayer {
  3066. YYAssertMainThread();
  3067. for (YYTextAttachment *a in self.attachments) {
  3068. if ([a.content isKindOfClass:[UIView class]]) {
  3069. UIView *v = a.content;
  3070. [v removeFromSuperview];
  3071. } else if ([a.content isKindOfClass:[CALayer class]]) {
  3072. CALayer *l = a.content;
  3073. [l removeFromSuperlayer];
  3074. }
  3075. }
  3076. }
  3077. @end