问题
- YYLabel如何刷新?
- YYLabel动态高度计算?
- 怎么获取高度?
- 不使用YYTextHighlight封装的高亮,事件响应会有问题吗?
- 事件是怎么回调的?
- 异步绘制逻辑?
- 不停的调用[self.layer setNeedsDisplay];会出现重复绘制的性能浪费吗?
问题1:YYLabel如何刷新?
下面一段是YYLabel的使用,是demo中的。
YYLabel *label = [YYLabel new];
label.attributedText = text;
label.width = self.view.width;
label.height = self.view.height - (kiOS7Later ? 64 : 44);
label.top = (kiOS7Later ? 64 : 0);
label.textAlignment = NSTextAlignmentCenter;
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
label.numberOfLines = 0;
label.backgroundColor = [UIColor colorWithWhite:0.933 alpha:1.000];
[self.view addSubview:label];
所有的属性设置都会调用下面的刷新方法
- (void)_setLayoutNeedRedraw {
[self.layer setNeedsDisplay];
}
YYLabel的layer层是YYTextAsyncLayer
+ (Class)layerClass {
return [YYTextAsyncLayer class];
}
调用完setNeedsDisplay,系统会在下一个runloop时调用display方法,也是真正的绘制方法。此方法在YYTextAsyncLayer中:
- (void)display {
super.contents = super.contents;
[self _displayAsync:_displaysAsynchronously];
}
_displayAsync中通过delegate又调回YYLabel中的newAsyncDisplayTask方法
- (YYTextAsyncLayerDisplayTask *)newAsyncDisplayTask {
...
task.willDisplay = ^(CALayer *layer) {
...
};
task.display = ^(CGContextRef context, CGSize size, BOOL (^isCancelled)(void)) {
...
[drawLayout drawInContext:context size:size point:point view:nil layer:nil debug:debug cancel:isCancelled];
};
task.didDisplay = ^(CALayer *layer, BOOL finished) {
...
};
return task;
}
- willDisplay的block块:移除@"contents"动画及attachmentViews与attachmentLayers层
- display的block块:就是真正的绘制功能。
- [drawLayout drawInContext:context size:size point:point view:nil layer:nil debug:debug cancel:isCancelled];
- didDisplay的block块进行动画的处理及图层移除.
关于CoreText不了解的,可以参考iOS CoreText文字图片排版及实现仿真翻页、iOS CoreText实现上下角标两篇文章。
简单介绍下:
YYTextLayout是排版引擎类,其中的YYTextDrawText是绘制文字的方法。
YYTextLine是每行的属性,YYTextDrawRun是每行的单个文字属性。其中的CTRunDraw就是系统提供的绘制方法。
CTRunDraw会把内容绘制在context上,最后生成image。
使用self.contents = (__bridge id)(image.CGImage)把生成的image赋值给YYTextAsyncLayer图层。
问题2:YYLabel动态高度计算?
与系统属性类似,提供一个宽度,设置numberOfLines=0。
yyLabel.numberOfLines = 0;
yyLabel.preferredMaxLayoutWidth = SCREEN_WIDTH-16*2;//设置最大宽度
设置完numberOfLines最后会触发display方法,绘制在newAsyncDisplayTask方法中的display块中
task.display = ^(CGContextRef context, CGSize size, BOOL (^isCancelled)(void)) {
...
YYTextLayout *drawLayout = layout;
if (layoutNeedUpdate) {
layout = [YYTextLayout layoutWithContainer:container text:text];
shrinkLayout = [YYLabel _shrinkLayoutWithLayout:layout];
if (isCancelled()) return;
layoutUpdated = YES;
drawLayout = shrinkLayout ? shrinkLayout : layout;
}
...
};
layoutWithContainer就是计算高度的方法,
+ (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range {
..
NSUInteger lineCurrentIdx = 0;
for (NSUInteger i = 0; i < lineCount; i++) {
CTLineRef ctLine = CFArrayGetValueAtIndex(ctLines, i);
CFArrayRef ctRuns = CTLineGetGlyphRuns(ctLine);
if (!ctRuns || CFArrayGetCount(ctRuns) == 0) continue;
// CoreText coordinate system
CGPoint ctLineOrigin = lineOrigins[i];
// UIKit coordinate system
CGPoint position;
position.x = cgPathBox.origin.x + ctLineOrigin.x;
position.y = cgPathBox.size.height + cgPathBox.origin.y - ctLineOrigin.y;
YYTextLine *line = [YYTextLine lineWithCTLine:ctLine position:position vertical:isVerticalForm];
CGRect rect = line.bounds;
if (constraintSizeIsExtended) {
if (isVerticalForm) {
if (rect.origin.x + rect.size.width >
constraintRectBeforeExtended.origin.x +
constraintRectBeforeExtended.size.width) break;
} else {
if (rect.origin.y + rect.size.height >
constraintRectBeforeExtended.origin.y +
constraintRectBeforeExtended.size.height) break;
}
}
BOOL newRow = YES;
if (rowMaySeparated && position.x != lastPosition.x) {
if (isVerticalForm) {
if (rect.size.width > lastRect.size.width) {
if (rect.origin.x > lastPosition.x && lastPosition.x > rect.origin.x - rect.size.width) newRow = NO;
} else {
if (lastRect.origin.x > position.x && position.x > lastRect.origin.x - lastRect.size.width) newRow = NO;
}
} else {
if (rect.size.height > lastRect.size.height) {
if (rect.origin.y < lastPosition.y && lastPosition.y < rect.origin.y + rect.size.height) newRow = NO;
} else {
if (lastRect.origin.y < position.y && position.y < lastRect.origin.y + lastRect.size.height) newRow = NO;
}
}
}
if (newRow) rowIdx++;
lastRect = rect;
lastPosition = position;
line.index = lineCurrentIdx;
line.row = rowIdx;
[lines addObject:line];
rowCount = rowIdx + 1;
lineCurrentIdx ++;
if (i == 0) textBoundingRect = rect;
else {
if (maximumNumberOfRows == 0 || rowIdx < maximumNumberOfRows) {
textBoundingRect = CGRectUnion(textBoundingRect, rect);
}
}
}
...
}
遍历每行的rect,求并集,textBoundingRect就是计算得出的高度。
问题3:怎么获取高度?
方法一:layoutWithContainerSize:text方法可计算高度
+ (YYTextLayout *)layoutWithContainerSize:(CGSize)size text:(NSAttributedString *)text {
YYTextContainer *container = [YYTextContainer containerWithSize:size];
return [self layoutWithContainer:container text:text];
}
但我认为这个方法不够优雅,因为在设置label属性的时候,高度就已经计算过了,再调用计算,会造成资源浪费。
方法二:[label setNeedsDisplay];
由问题一我们了解,设置属性后,会调用_setLayoutNeedUpdate,然后在下一个runloop由系统调用display进行绘制。
使用setNeedsDisplay强制绘制,再使用CGSize size = label.textLayout.textBoundingSize;属性获取size即可
[label setNeedsDisplay];
CGSize size = label.textLayout.textBoundingSize;
方法三:在异步主队列中获取高度
该方法与方法二都是解决view没有及时刷新的解决方案。
dispatch_async(dispatch_get_main_queue(), ^{
CGSize size = label.textLayout.textBoundingSize;
});
问题4:不使用YYTextHighlight封装的高亮,事件响应会有问题吗?
由于富文本我已经封装成链式组件:WPChained,下面是调用。
NSRange range = [text rangeOfString:obj.text];
[attributedString wp_makeAttributed:^(WPMutableAttributedStringMaker * _Nullable make) {
make.textColor([UIColor blueColor],range);
make.underlineStyle(NSUnderlineStyleSingle,[UIColor blueColor],range);
}];
本着高亮不使用YYTextHighlight对象,能捕捉到点击事件吗?
下面一段是使用YYTextHighlight设置高亮并回调事件的代码
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setColor:[UIColor whiteColor]];
[highlight setBackgroundBorder:highlightBorder]; highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
[_self showMessage:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
};
[one yy_setTextHighlight:highlight range:one.yy_rangeOfAll];
- (void)yy_setTextHighlight:(YYTextHighlight *)textHighlight range:(NSRange)range {
[self yy_setAttribute:YYTextHighlightAttributeName value:textHighlight range:range];
}
- (void)yy_setAttribute:(NSString *)name value:(id)value range:(NSRange)range {
if (!name || [NSNull isEqual:name]) return;
if (value && ![NSNull isEqual:value]) [self addAttribute:name value:value range:range];
else [self removeAttribute:name range:range];
}
YYTextHighlight 使用自定义的YYTextHighlightAttributeName设置富文本的属性。
使用系统提供的enumerateAttributesInRange:方法遍历富文本,判断是否有高亮,设置containsHighlight为YES,在绘制时绘制高亮。
void (^block)(NSDictionary *attrs, NSRange range, BOOL *stop) = ^(NSDictionary *attrs, NSRange range, BOOL *stop) {
if (attrs[YYTextHighlightAttributeName]) layout.containsHighlight = YES;
if (attrs[YYTextBlockBorderAttributeName]) layout.needDrawBlockBorder = YES;
if (attrs[YYTextBackgroundBorderAttributeName]) layout.needDrawBackgroundBorder = YES;
if (attrs[YYTextShadowAttributeName] || attrs[NSShadowAttributeName]) layout.needDrawShadow = YES;
if (attrs[YYTextUnderlineAttributeName]) layout.needDrawUnderline = YES;
if (attrs[YYTextAttachmentAttributeName]) layout.needDrawAttachment = YES;
if (attrs[YYTextInnerShadowAttributeName]) layout.needDrawInnerShadow = YES;
if (attrs[YYTextStrikethroughAttributeName]) layout.needDrawStrikethrough = YES;
if (attrs[YYTextBorderAttributeName]) layout.needDrawBorder = YES;
};
[layout.text enumerateAttributesInRange:visibleRange options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:block];
在touchesBegan获取高亮对象
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
...
_highlight = [self _getHighlightAtPoint:point range:&_highlightRange];
...
}
在_getHighlightAtPoint根据自定义的YYTextHighlightAttributeName属性获取YYTextHighlight对象
- (YYTextHighlight *)_getHighlightAtPoint:(CGPoint)point range:(NSRangePointer)range {
...
NSRange highlightRange = {0};
YYTextHighlight *highlight = [_innerText attribute:YYTextHighlightAttributeName
atIndex:startIndex
longestEffectiveRange:&highlightRange
inRange:NSMakeRange(0, _innerText.length)];
if (!highlight) return nil;
if (range) *range = highlightRange;
return highlight;
}
由此可见,还是要乖乖的使用YYTextHighlight,对象都没有,点击事件怎么会响应。
问题5:事件是怎么回调的?
问题4只是了解了设置高亮与获取高亮对象,点击事件呢?
在touchesEnded中有点击事件
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = touches.anyObject;
CGPoint point = [touch locationInView:self];
if (_state.trackingTouch) {
[self _endLongPressTimer];
if (!_state.touchMoved && _textTapAction) {
NSRange range = NSMakeRange(NSNotFound, 0);
CGRect rect = CGRectNull;
CGPoint point = [self _convertPointToLayout:_touchBeganPoint];
YYTextRange *textRange = [self._innerLayout textRangeAtPoint:point];
CGRect textRect = [self._innerLayout rectForRange:textRange];
textRect = [self _convertRectFromLayout:textRect];
if (textRange) {
range = textRange.asRange;
rect = textRect;
}
_textTapAction(self, _innerText, range, rect);
}
if (_highlight) {
if (!_state.touchMoved || [self _getHighlightAtPoint:point range:NULL] == _highlight) {
YYTextAction tapAction = _highlight.tapAction ? _highlight.tapAction : _highlightTapAction;
if (tapAction) {
YYTextPosition *start = [YYTextPosition positionWithOffset:_highlightRange.location];
YYTextPosition *end = [YYTextPosition positionWithOffset:_highlightRange.location + _highlightRange.length affinity:YYTextAffinityBackward];
YYTextRange *range = [YYTextRange rangeWithStart:start end:end];
CGRect rect = [self._innerLayout rectForRange:range];
rect = [self _convertRectFromLayout:rect];
tapAction(self, _innerText, _highlightRange, rect);
}
}
[self _removeHighlightAnimated:_fadeOnHighlight];
}
}
if (!_state.swallowTouch) {
[super touchesEnded:touches withEvent:event];
}
}
问题6.异步绘制逻辑?
回到刚才绘制的方法_displayAsync
- (void)_displayAsync:(BOOL)async {
if (async) {
if (task.willDisplay) task.willDisplay(self);
_YYTextSentinel *sentinel = _sentinel;
int32_t value = sentinel.value;
BOOL (^isCancelled)() = ^BOOL() {
return value != sentinel.value;
};
CGSize size = self.bounds.size;
BOOL opaque = self.opaque;
CGFloat scale = self.contentsScale;
CGColorRef backgroundColor = (opaque && self.backgroundColor) ? CGColorRetain(self.backgroundColor) : NULL;
if (size.width < 1 || size.height < 1) {
CGImageRef image = (__bridge_retained CGImageRef)(self.contents);
self.contents = nil;
if (image) {
dispatch_async(YYTextAsyncLayerGetReleaseQueue(), ^{
CFRelease(image);
});
}
if (task.didDisplay) task.didDisplay(self, YES);
CGColorRelease(backgroundColor);
return;
}
dispatch_async(YYTextAsyncLayerGetDisplayQueue(), ^{
if (isCancelled()) {
CGColorRelease(backgroundColor);
return;
}
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (opaque && context) {
CGContextSaveGState(context); {
if (!backgroundColor || CGColorGetAlpha(backgroundColor) < 1) {
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale));
CGContextFillPath(context);
}
if (backgroundColor) {
CGContextSetFillColorWithColor(context, backgroundColor);
CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale));
CGContextFillPath(context);
}
} CGContextRestoreGState(context);
CGColorRelease(backgroundColor);
}
task.display(context, size, isCancelled);
if (isCancelled()) {
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
if (task.didDisplay) task.didDisplay(self, NO);
});
return;
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (isCancelled()) {
dispatch_async(dispatch_get_main_queue(), ^{
if (task.didDisplay) task.didDisplay(self, NO);
});
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (isCancelled()) {
if (task.didDisplay) task.didDisplay(self, NO);
} else {
self.contents = (__bridge id)(image.CGImage);
if (task.didDisplay) task.didDisplay(self, YES);
}
});
});
} else {
...
}
}
上面整个绘制生成image的过程在子线程中,最后赋值给self.contents回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
if (isCancelled()) {
if (task.didDisplay) task.didDisplay(self, NO);
} else {
self.contents = (__bridge id)(image.CGImage);
if (task.didDisplay) task.didDisplay(self, YES);
}
});
问题7:不停的调用[self.layer setNeedsDisplay];会出现重复绘制的性能浪费吗?
不会,每一个属性设置最终都调到了setNeedsDisplay,调用完后不会立马刷新。会等到下一个runloop唤醒时进行display。这样也保证了属性调用完一定会刷新UI。
总结:
- YY系列源码代码质量高,非常值得去阅读。
- 更多细节还需慢慢品读,有任何问题欢迎留言交流。
YYLabel的绘制
1.生成NSMutableAttributedString
1.YYTextAttribute
文本包含一些基本属性,YYTextShadow、YYTextBorder、YYTextHighlight、YYTextAttachment等。都被封装成对象。
NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"Border"];
one.yy_font = [UIFont boldSystemFontOfSize:30];
one.yy_color = [UIColor colorWithRed:1.000 green:0.029 blue:0.651 alpha:1.000];
YYTextBorder *border = [YYTextBorder new];
border.strokeColor = [UIColor colorWithRed:1.000 green:0.029 blue:0.651 alpha:1.000];
border.strokeWidth = 3;
border.lineStyle = YYTextLineStylePatternCircleDot;
border.cornerRadius = 3;
border.insets = UIEdgeInsetsMake(0, -4, 0, -4);
one.yy_textBackgroundBorder = border;
[text appendAttributedString:one];
2.yy_textBackgroundBorder
YYTextBackgroundBorderAttributeName 是重点,后面会用到。
- (void)yy_setTextBackgroundBorder:(YYTextBorder *)textBackgroundBorder range:(NSRange)range {
[self yy_setAttribute:YYTextBackgroundBorderAttributeName value:textBackgroundBorder range:range];
}
2.YYLabel、YYTextAsyncLayer、YYTextLayout
- 构建NSMutableAttributedString完成后,在YYLabel中会调用_setLayoutNeedRedraw。
- (void)_setLayoutNeedRedraw {
NSLog(@"_setLayoutNeedRedraw");
[self.layer setNeedsDisplay];
}
- 触发YYTextAsyncLayer中的display方法
- (void)display {
NSLog(@"display");
super.contents = super.contents;
[self _displayAsync:_displaysAsynchronously];
}
- (void)_displayAsync:(BOOL)async {
__strong id<YYTextAsyncLayerDelegate> delegate = (id)self.delegate;
YYTextAsyncLayerDisplayTask *task = [delegate newAsyncDisplayTask];
...
}
- YYLabel中的newAsyncDisplayTask
task.display = ^(CGContextRef context, CGSize size, BOOL (^isCancelled)(void)) {
if (isCancelled()) return;
if (text.length == 0) return;
YYTextLayout *drawLayout = layout;
if (layoutNeedUpdate) {
layout = [YYTextLayout layoutWithContainer:container text:text];
shrinkLayout = [YYLabel _shrinkLayoutWithLayout:layout];
if (isCancelled()) return;
layoutUpdated = YES;
drawLayout = shrinkLayout ? shrinkLayout : layout;
}
...
}
- YYTextLayout中的layoutWithContainer
[layoutWithContainer:]进行计算;把NSAttributedString转换成CTFramesetterRef->CTFrameRef->YYTextLine、YYTextAttachment等。
+ (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range {
...
}
- drawInContext绘制
- (void)drawInContext:(CGContextRef)context
size:(CGSize)size
point:(CGPoint)point
view:(UIView *)view
layer:(CALayer *)layer
debug:(YYTextDebugOption *)debug
cancel:(BOOL (^)(void))cancel{
@autoreleasepool {
if (!context) {
return;
}
if (cancel && cancel()) return;
if (self.needDrawBlockBorder) {
YYTextDrawBlockBorder(self, context, size, point, cancel);
}
if (self.needDrawBackgroundBorder) {
YYTextDrawBorder(self, context, size, point, YYTextBorderTypeBackgound, cancel);
}
if (self.needDrawShadow) {
YYTextDrawShadow(self, context, size, point, cancel);
}
if (self.needDrawUnderline) {
YYTextDrawDecoration(self, context, size, point, YYTextDecorationTypeUnderline, cancel);
}
if (self.needDrawText) {
YYTextDrawText(self, context, size, point, cancel);
}
if (self.needDrawAttachment && (context || view || layer)) {
YYTextDrawAttachment(self, context, size, point, view, layer, cancel);
}
if (self.needDrawInnerShadow) {
YYTextDrawInnerShadow(self, context, size, point, cancel);
}
if (self.needDrawStrikethrough) {
YYTextDrawDecoration(self, context, size, point, YYTextDecorationTypeStrikethrough, cancel);
}
if (self.needDrawBorder) {
YYTextDrawBorder(self, context, size, point, YYTextBorderTypeNormal, cancel);
}
if (debug.needDrawDebug) {
YYTextDrawDebug(self, context, size, point, debug);
}
}
}
YYLabel附件绘制源码阅读:UIImage、UIView、CALayer绘制原理
1.设置content及代理
+ (NSMutableAttributedString *)yy_attachmentStringWithContent:(id)content
contentMode:(UIViewContentMode)contentMode
attachmentSize:(CGSize)attachmentSize
alignToFont:(UIFont *)font
alignment:(YYTextVerticalAlignment)alignment {
NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken];//占位
YYTextAttachment *attach = [YYTextAttachment new];
attach.content = content;
attach.contentMode = contentMode;
[atr yy_setTextAttachment:attach range:NSMakeRange(0, atr.length)];
YYTextRunDelegate *delegate = [YYTextRunDelegate new];
delegate.width = attachmentSize.width;
switch (alignment) {
case YYTextVerticalAlignmentTop: {
delegate.ascent = font.ascender;
delegate.descent = attachmentSize.height - font.ascender;
if (delegate.descent < 0) {
delegate.descent = 0;
delegate.ascent = attachmentSize.height;
}
} break;
case YYTextVerticalAlignmentCenter: {
CGFloat fontHeight = font.ascender - font.descender;
CGFloat yOffset = font.ascender - fontHeight * 0.5;
delegate.ascent = attachmentSize.height * 0.5 + yOffset;
delegate.descent = attachmentSize.height - delegate.ascent;
if (delegate.descent < 0) {
delegate.descent = 0;
delegate.ascent = attachmentSize.height;
}
} break;
case YYTextVerticalAlignmentBottom: {
delegate.ascent = attachmentSize.height + font.descender;
delegate.descent = -font.descender;
if (delegate.ascent < 0) {
delegate.ascent = 0;
delegate.descent = attachmentSize.height;
}
} break;
default: {
delegate.ascent = attachmentSize.height;
delegate.descent = 0;
} break;
}
CTRunDelegateRef delegateRef = delegate.CTRunDelegate;
[atr yy_setRunDelegate:delegateRef range:NSMakeRange(0, atr.length)];
if (delegate) CFRelease(delegateRef);
return atr;
}
- (void)yy_setTextAttachment:(YYTextAttachment *)textAttachment range:(NSRange)range {
[self yy_setAttribute:YYTextAttachmentAttributeName value:textAttachment range:range];
}
- 构建YYTextAttachment对象,并赋值content
- yy_setTextAttachment设置后,后面能在遍历CTRun时通过YYTextAttachmentAttributeName找到对应的YYTextAttachment
2.YYTextLine
//YYTextLine
- (void)reloadBounds {
...
for (NSUInteger r = 0; r < runCount; r++) {
CTRunRef run = CFArrayGetValueAtIndex(runs, r);
CFIndex glyphCount = CTRunGetGlyphCount(run);
if (glyphCount == 0) continue;
NSDictionary *attrs = (id)CTRunGetAttributes(run);
YYTextAttachment *attachment = attrs[YYTextAttachmentAttributeName];
...
}
}
_attachments = attachments.count ? attachments : nil;
_attachmentRanges = attachmentRanges.count ? attachmentRanges : nil;
_attachmentRects = attachmentRects.count ? attachmentRects : nil;
}
遍历CTRunRef,根据CTYYTextAttachmentAttributeName取到YYTextAttachment,计算ranges,rects等属性。追加到数组中。
3.绘制
static void YYTextDrawAttachment(YYTextLayout *layout, CGContextRef context, CGSize size, CGPoint point, UIView *targetView, CALayer *targetLayer, BOOL (^cancel)(void)) {
BOOL isVertical = layout.container.verticalForm;
CGFloat verticalOffset = isVertical ? (size.width - layout.container.size.width) : 0;
for (NSUInteger i = 0, max = layout.attachments.count; i < max; i++) {
YYTextAttachment *a = layout.attachments[i];
if (!a.content) continue;
UIImage *image = nil;
UIView *view = nil;
CALayer *layer = nil;
if ([a.content isKindOfClass:[UIImage class]]) {
image = a.content;
} else if ([a.content isKindOfClass:[UIView class]]) {
view = a.content;
} else if ([a.content isKindOfClass:[CALayer class]]) {
layer = a.content;
}
if (!image && !view && !layer) continue;
if (image && !context) continue;
if (view && !targetView) continue;
if (layer && !targetLayer) continue;
if (cancel && cancel()) break;
CGSize asize = image ? image.size : view ? view.frame.size : layer.frame.size;
CGRect rect = ((NSValue *)layout.attachmentRects[i]).CGRectValue;
if (isVertical) {
rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetRotateVertical(a.contentInsets));
} else {
rect = UIEdgeInsetsInsetRect(rect, a.contentInsets);
}
rect = YYTextCGRectFitWithContentMode(rect, asize, a.contentMode);
rect = YYTextCGRectPixelRound(rect);
rect = CGRectStandardize(rect);
rect.origin.x += point.x + verticalOffset;
rect.origin.y += point.y;
if (image) {
CGImageRef ref = image.CGImage;
if (ref) {
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, CGRectGetMaxY(rect) + CGRectGetMinY(rect));
CGContextScaleCTM(context, 1, -1);
CGContextDrawImage(context, rect, ref);
CGContextRestoreGState(context);
}
} else if (view) {
view.frame = rect;
[targetView addSubview:view];
} else if (layer) {
layer.frame = rect;
[targetLayer addSublayer:layer];
}
}
}
遍历attachments,view和layer直接添加到targetView或targetLayer;UIImage使用CGContext绘制。