iOS使用CoreText绘制label

什么是异步绘制?
在子线程中绘制需要显示的内容、不占用主线程资源以防绘制的过程中阻塞主线程。
对UIView来说即绘制其layer.contents的内容。

为什么要使用异步绘制?
如果在主线程中直接绘制有可能会阻塞主线程、导致fps降低(尤其是当在cell中使用时)、影响app的使用体验。

如何进行异步绘制?
话不多说、直接上代码:https://github.com/Avery-AN/TableView (QAAttributedLayer中使用了异步绘制)

QAAttributedLayer


QAAttributedLayer中异步绘制的主要实现方案

QAAttributedLabel为何而生?
主要是实现类似于微博app首页cell中的富文本的效果、并支持单击交互。


效果图1

效果图2


主要实现的功能

支持高亮文案点击时的圆角背景
支持url高亮显示、支持url点击效果的高亮显示、支持自定义url的字体
支持url自定义短链接文案
支持@xxx高亮显示、支持@xxx点击效果的高亮显示、支持自定义@xxx的字体
支持#xxx#高亮显示、支持#xxx#点击效果的高亮显示、支持自定义#xxx#的字体
支持自定义的Emoji显示
支持固定文本的高亮显示
支持搜索文本的高亮显示
支持同步、异步绘制
使用CoreText绘制、可自定义各种富文本样式(行间距、字间距、段间距等)
支持对超长文案的截断处理 (ps:将超长文案的末尾处理成:"...全文"、并且支持自定义此截断文案)
支持高亮文案的交互

使用时需要创建QARichTextLabel 或者 TrapezoidalLabel这两个类的对象。
QARichTextLabel主要是实现微博首页那种的富文本展示、而TrapezoidalLabel这个类主要是实现一些异形的label (见上面的效果图2)。


具体的实现

QAAttributedLabel这个类是QARichTextLabel 或者 TrapezoidalLabel这两个类的父类,这个类中定义了各种富文本的属性,在使用时直接赋值即可。

@interface QAAttributedLabel : UIView
@property (nonatomic, copy, nullable) NSString *text;
@property (nonatomic, copy, nullable) NSMutableAttributedString *attributedString;  // 若text也同时存在则优先显示attributedString
@property (nonatomic, strong, nullable, readonly) NSMutableAttributedString *srcAttributedString;
@property (nonatomic, copy, nullable) UIFont *font;
@property (nonatomic, copy, null_resettable) UIColor *textColor;
@property (nonatomic, assign) BOOL noRichTexts;                     // 不处理富文本(默认为NO)
@property (nonatomic, assign, readonly) NSInteger length;           // 显示文案的长度
@property (nonatomic, assign) NSTextAlignment textAlignment;        // 文本的对齐方式
@property (nonatomic, assign) NSLineBreakMode lineBreakMode;        // 换行模式
@property (nonatomic, assign) NSUInteger numberOfLines;             // 需要显示文本的行数
@property (nonatomic, assign) CGFloat paragraphSpace;               // 段间距
@property (nonatomic, assign) CGFloat lineSpace;                    // 行间距
@property (nonatomic, assign) int wordSpace;                        // 字间距
@property (nonatomic, assign) BOOL display_async;           // 是否异步绘制 (默认为NO)
@property (nonatomic, assign) BOOL linkHighlight;           // 网页链接是否需要高亮显示 (默认为NO)
@property (nonatomic, assign) BOOL showShortLink;           // 是否展示短链接 ("https://www.avery.com" -> "网页短链接"; 默认为NO)
@property (nonatomic, assign) BOOL atHighlight;             // "@xxx"是否需要高亮显示 (默认为NO)
@property (nonatomic, assign) BOOL topicHighlight;          // "#话题#"是否需要高亮显示 (默认为NO)
@property (nonatomic, assign) BOOL showMoreText;            // 当文本过多时、是否显示seeMoreText的内容 (默认为NO)
@property (nonatomic, assign, readonly) BOOL isTouching;    // 是否正在被点击 (touchesBegan时为YES、touches事件结束后为NO)
@property (nonatomic, copy, nullable) NSString *shortLink;                      // 展示短链接时显示的文案 (PS:"网页链接"、"网址"等)
@property (nonatomic, copy, nullable) NSArray *highLightTexts;                  // text文本中需要高亮显示的部分
@property (nonatomic, copy, nullable) UIFont *highlightFont;                    // 高亮文案的字体
@property (nonatomic, copy, nullable) UIColor *highlightTextColor;              // 高亮显示时的颜色 (其它几种高亮情况的默认颜色)
@property (nonatomic, copy, nullable) UIColor *highlightLinkTextColor;          // 高亮显示时的颜色 (link)
@property (nonatomic, copy, nullable) UIColor *highlightAtTextColor;            // 高亮显示时的颜色 (at)
@property (nonatomic, copy, nullable) UIColor *highlightTopicTextColor;         // 高亮显示时的颜色 (topic)
@property (nonatomic, copy, nullable) UIColor *highlightTapedTextColor;         // 点击高亮文案时的字体颜色 (其它几种情况的默认颜色)
@property (nonatomic, copy, nullable) UIColor *highlightLinkTapedTextColor;     // 点击高亮文案时的字体颜色 (link)
@property (nonatomic, copy, nullable) UIColor *highlightAtTapedTextColor;       // 点击高亮文案时的字体颜色 (at)
@property (nonatomic, copy, nullable) UIColor *highlightTopicTapedTextColor;    // 点击高亮文案时的字体颜色 (topic)
@property (nonatomic, copy, nullable) UIColor *highlightTextBackgroundColor;    // 高亮文案的背景颜色
@property (nonatomic, copy, nullable) UIColor *highlightTapedBackgroundColor;   // 点击高亮文案时的背景色

/**
 显示seeMoreText的前提条件:
 (1) showMoreText = YES;
 (2) 展示当前显示文案所需的lines大于所设置的numberOfLines;
 */
@property (nonatomic, copy, nullable) NSString *seeMoreText;                // PS:"...查看全文" 或者 "...全文"
@property (nonatomic, copy, nullable) UIFont *moreTextFont;                 // seeMoreText的字体
@property (nonatomic, copy, nullable) UIColor *moreTextColor;               // seeMoreText的字体颜色
@property (nonatomic, copy, nullable) UIColor *moreTextBackgroundColor;     // seeMoreText的背景颜色
@property (nonatomic, copy, nullable) UIColor *moreTapedBackgroundColor;    // 点击seeMoreText时的背景颜色
@property (nonatomic, copy, nullable) UIColor *moreTapedTextColor;          // 点击seeMoreText时的字体颜色

@property (nonatomic, strong, nullable) QATextLayout *textLayout;
@property (nonatomic, copy) void (^ _Nullable QAAttributedLabelTapAction)(NSString * _Nullable content, QAAttributedLabel_TapedStyle style);
@property (nonatomic, copy, nullable) GetTextContentSizeBlock getTextContentSizeBlock;

/**
 label已渲染完毕后、若再次更改其属性此值为被设为YES、并且后续还会调用layer的updateContent方法
 */
@property (nonatomic, assign) BOOL needUpdate;

/**
 获取文案所占用的size
 */
- (void)getTextContentSizeWithLayer:(id _Nonnull)layer
                            content:(id _Nonnull)content
                           maxWidth:(CGFloat)width
                    completionBlock:(GetTextContentSizeBlock _Nullable)block;

/**
 设置layer的contents
 @param image layer的contents需要显示的图片
 @param attributedString 与image相对应的富文本字符串
 PS: attributedString的作用主要是为了计算highlightRanges & highlightFonts & highlightFrameDic等、以备点击高亮字体时使用
 */
- (void)setContentsImage:(UIImage * _Nonnull)image
        attributedString:(NSMutableAttributedString * _Nonnull)attributedString;

/**
 搜索文案
 */
- (void)searchTexts:(NSArray * _Nonnull)texts resetSearchResultInfo:(NSDictionary * _Nullable (^_Nullable)(void))searchResultInfo;

// 点击事件是否击中了高亮文本
- (BOOL)isHitHighlightTextWithPoint:(CGPoint)point
                      highlightRect:(CGRect)highlightRect
                     highlightRange:(NSString * _Nonnull)rangeString;

- (CGSize)getContentSize;
- (CGImageRef _Nullable )getLayerContents;

@end



QAAttributedLayer这个类主要是负责显示内容的同步/异步绘制。

- (void)fillContents_async:(QAAttributedLabel *)attributedLabel {   // 异步绘制
    dispatch_async(QAAttributedLayerDrawQueue(), ^{
        self.contents = cgImage;
    });
}
- (void)fillContents_sync:(QAAttributedLabel *)attributedLabel {   // 同步绘制
}

绘制过程主要分为2步、第一步是将显示的文案处理成NSMutableAttributedString、第二步是对NSMutableAttributedString进行绘制。
下面将以异步绘制来说下绘制的过程:
首先根据label设置的各种属性值来获取NSMutableAttributedString并给赋值上各种富文本属性;
在获取NSMutableAttributedString的过程中会保存需要高亮显示的文案与位置 & 自定义的Emoji & 是否要对文案的结尾进行处理(处理成"...全文")等相关信息;
这里需要说下:保存相关高亮文案的信息以及位置的主要目的是用于label的交互。
绘制的过程是在QATextDraw类中进行处理的、主要包括NSMutableAttributedString以及自定义的emoji的绘制;
QABackgroundDraw主要是负责绘制圆角背景;


下面说一下代码中几个需要注意的点

(1) 为什么使用QAAttributedLayerDrawQueue()而不使用dispatch_get_global_queue()?
dispatch_async(QAAttributedLayerDrawQueue(), ^{
    // 提交异步处理
});

因为系统本身和Project中的其他地方也会在dispatch_get_global_queue中请求新线程、一个队列中可以开辟的线程数是有限的,所以当你在dispatch_get_global_queue中大量的开辟线程时有可能会导致堵塞、从而导致线程不能正常执行。

(2) 为什么用CATransaction而不是切回到主线程?
dispatch_async(QAAttributedLayerDrawQueue(), ^{
    self.contents = (__bridge id)(cgImage);
    [CATransaction commit];
});

// 而没有这样做:
dispatch_async(QAAttributedLayerDrawQueue(), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.contents = (__bridge id)(cgImage);
    });
});

具体请看另一篇文章:iOS中的CATransaction是干什么的



【 请勿直接转载 - 节约能源从你我做起 】

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。