天天看點

CATextLayer繪制文本字元串

CATextLayer使用Core Text進行繪制,渲染速度比使用Web Kit的UILable快很多。而且UILable主要是管理内容,而CATextLayer則是繪制内容。

CATextLayer的繪制文本字元串的效果如下:

CATextLayer繪制文本字元串

代碼示例:

// 繪制文本的圖層
CATextLayer *layerText = [[CATextLayer alloc] init];
// 背景顔色
layerText.backgroundColor = [UIColor orangeColor].CGColor;
// 渲染分辨率-重要,否則顯示模糊
layerText.contentsScale = [UIScreen mainScreen].scale;
// 顯示位置
layerText.bounds = CGRectMake(0.0, 0.0, 100.0, 50.0);
layerText.position = position;
// 添加到父圖書
[self.view.layer addSublayer:layerText];
           
// 分行顯示
layerText.wrapped = YES;
// 超長顯示時,省略号位置
layerText.truncationMode = kCATruncationNone;
// 字型顔色
layerText.foregroundColor = [UIColor purpleColor].CGColor;
// 字型名稱、大小
UIFont *font = [UIFont systemFontOfSize:15.0];
CFStringRef fontName = (__bridge CFStringRef)font.fontName;
CGFontRef fontRef =CGFontCreateWithFontName(fontName);
layerText.font = fontRef;
layerText.fontSize = font.pointSize;
CGFontRelease(fontRef);
// 字型對方方式
layerText.alignmentMode = kCAAlignmentJustified;
           
// 字元顯示
NSString *text = @"devZhang is iOSDeveloper.devZhang is iOSDeveloper.devZhang is iOSDeveloper.devZhang is iOSDeveloper.";
           
// 方法1-簡單顯示
layerText.string = text;
           
// 方法2-富文本顯示
// 文本段落樣式
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle alloc] init];
textStyle.lineBreakMode = NSLineBreakByWordWrapping; // 結尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")
textStyle.alignment = NSTextAlignmentCenter; //(兩端對齊的)文本對齊方式:(左,中,右,兩端對齊,自然)
textStyle.lineSpacing = 5; // 字型的行間距
textStyle.firstLineHeadIndent = 5.0; // 首行縮進
textStyle.headIndent = 0.0; // 整體縮進(首行除外)
textStyle.tailIndent = 0.0; //
textStyle.minimumLineHeight = 20.0; // 最低行高
textStyle.maximumLineHeight = 20.0; // 最大行高
textStyle.paragraphSpacing = 15; // 段與段之間的間距
textStyle.paragraphSpacingBefore = 22.0f; // 段首行空白空間/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */
textStyle.baseWritingDirection = NSWritingDirectionLeftToRight; // 從左到右的書寫方向(一共➡️三種)
textStyle.lineHeightMultiple = 15; /* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */
textStyle.hyphenationFactor = 1; //連字屬性 在iOS,唯一支援的值分别為0和1
// 文本屬性
NSMutableDictionary *textAttributes = [[NSMutableDictionary alloc] init];
// NSParagraphStyleAttributeName 段落樣式
[textAttributes setValue:textStyle forKey:NSParagraphStyleAttributeName];
// NSFontAttributeName 字型名稱和大小
[textAttributes setValue:[UIFont systemFontOfSize:12.0] forKey:NSFontAttributeName];
// NSForegroundColorAttributeNam 顔色
[textAttributes setValue:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
[attributedText setAttributes:textAttributes range:NSMakeRange(0, 8)];
layerText.string = attributedText;
           

繼續閱讀