我用以下几个问题去阅读YYLabel的源码:
问题1:YYLabel如何刷新?
问题2:YYLabel动态高度计算?
问题3:怎么获取高度?
问题4:不使用YYTextHighlight封装的高亮,事件响应会有问题吗?
问题5:事件是怎么回调的?
问题6.异步绘制逻辑?
问题7:不停的调用[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实现上下角标两篇文章。
简单介绍下:
1.YYTextLayout是排版引擎类,其中的YYTextDrawText是绘制文字的方法。
2.YYTextLine是每行的属性,YYTextDrawRun是每行的单个文字属性。其中的CTRunDraw就是系统提供的绘制方法。
3.CTRunDraw会把内容绘制在context上,最后生成image。
4.使用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系列源码代码质量高,非常值得去阅读。
- 更多细节还需慢慢品读,有任何问题欢迎留言交流。
网友评论