一、CATextLayer简介
CATextLayer可以通过字符串进行文字的绘制。
二、CATextLayer.h属性
//渲染的文字字符串
@property(nullable, copy) id string;
//设置字体
@property(nullable) CFTypeRef font;
//设置字号
@property CGFloat fontSize;
//设置文字颜色
@property(nullable) CGColorRef foregroundColor;
//是否换行
@property(getter=isWrapped) BOOL wrapped;
/*
设置截断模式
NSString * const kCATruncationNone;
截断前部分
NSString * const kCATruncationStart;
截断后部分
NSString * const kCATruncationEnd;
截断中间
NSString * const kCATruncationMiddle;
*/
@property(copy) NSString *truncationMode;
/*
设置文字对齐模式
NSString * const kCAAlignmentNatural;
NSString * const kCAAlignmentLeft;
NSString * const kCAAlignmentRight;
NSString * const kCAAlignmentCenter;
NSString * const kCAAlignmentJustified;
*/
@property(copy) NSString *alignmentMode;
三、实例
1、简单使用
NSString*str=@"HELLO WORLD !";
NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
[attriString addAttribute:NSForegroundColorAttributeName value:(id)[UIColor brownColor].CGColor range:NSMakeRange(0,1)];
[attriString addAttribute:(NSString *)NSForegroundColorAttributeName
value:(id)[UIColor redColor].CGColor
range:NSMakeRange(1, 2)];
[attriString addAttribute:(NSString *)NSForegroundColorAttributeName value:(id)[UIColor blueColor].CGColor range:NSMakeRange(2,str.length-2)];
CATextLayer *textLayer = [CATextLayer layer];
textLayer.string = attriString;
textLayer.alignmentMode=kCAAlignmentCenter;
textLayer.fontSize=20;
textLayer.frame = CGRectMake(0, 120, ScreenWidth, 20);
textLayer.backgroundColor=[[UIColor darkGrayColor]CGColor];
textLayer.wrapped=YES;
textLayer.contentsScale = [UIScreen mainScreen].scale;
[self.view.layer addSublayer:textLayer];
结果如下:

四、使用中遇到的问题
1、字体模糊的问题
这是文本像素化了,它没有以Retina的方式渲染,而contentScale这个属性,用来决定图层内容应该以怎样的分辨率来渲染。contentsScale并不关心屏幕的拉伸因素而总是默认为1.0。如果我们想以Retina的质量来显示文字,我们就得手动地设置CATextLayer的contentsScale属性,如下:
layer.contentsScale = [UIScreen mainScreen].scale;
效果如图:

网友评论