美文网首页iOS开发CALayerQuartzCore框架
iOS[QuartzCore框架](CATextLayer)(6

iOS[QuartzCore框架](CATextLayer)(6

作者: 一只小蝉儿 | 来源:发表于2016-07-21 15:49 被阅读721次

一、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];

结果如下:


屏幕快照 2016-07-21 下午3.25.41.png

四、使用中遇到的问题

1、字体模糊的问题

这是文本像素化了,它没有以Retina的方式渲染,而contentScale这个属性,用来决定图层内容应该以怎样的分辨率来渲染。contentsScale并不关心屏幕的拉伸因素而总是默认为1.0。如果我们想以Retina的质量来显示文字,我们就得手动地设置CATextLayer的contentsScale属性,如下:

layer.contentsScale = [UIScreen mainScreen].scale;

效果如图:


6.3.png

相关文章

网友评论

本文标题:iOS[QuartzCore框架](CATextLayer)(6

本文链接:https://www.haomeiwen.com/subject/buubjttx.html