iOS 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;
}
  1. willDisplay的block块:移除@"contents"动画及attachmentViews与attachmentLayers层
  2. display的block块:就是真正的绘制功能。
  3. [drawLayout drawInContext:context size:size point:point view:nil layer:nil debug:debug cancel:isCancelled];
  4. 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。

总结:

  1. YY系列源码代码质量高,非常值得去阅读。
  2. 更多细节还需慢慢品读,有任何问题欢迎留言交流。

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

  1. 构建NSMutableAttributedString完成后,在YYLabel中会调用_setLayoutNeedRedraw。
- (void)_setLayoutNeedRedraw {
    NSLog(@"_setLayoutNeedRedraw");
    [self.layer setNeedsDisplay];
}
  1. 触发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];
    ...
}
  1. 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;
    }
    ...
}
  1. YYTextLayout中的layoutWithContainer
    [layoutWithContainer:]进行计算;把NSAttributedString转换成CTFramesetterRef->CTFrameRef->YYTextLine、YYTextAttachment等。
+ (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range {
     ...
}
  1. 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绘制原理

image

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];
}
  1. 构建YYTextAttachment对象,并赋值content
  2. 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绘制。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容