坐标系
如果你了解过 iOS UIKit,你就知道坐标的原点就在屏幕的左上角,但是底层Core Graphics的context使用的坐标系的原点是在屏幕的左下角。那从底层到上层一定是做了转变。苹果官方例图
上图可以看到,坐标系发生了改变,变成了我们最熟悉的模样。具体代码实现如下:
- (void)drawRect:(CGRect)rect{
[super drawRect:rect];
//获得当前的Graphics Context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
//向上平移一个视图高度的距离
CGContextTranslateCTM(context, 0, self.bounds.size.height);
//围绕x轴的翻转
CGContextScaleCTM(context, 1.0, -1.0);
}
写一小段文字效果:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
//获得当前的Graphics Context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
//向上平移一个视图高度的距离
CGContextTranslateCTM(context, 0, self.bounds.size.height);
//围绕x轴的翻转
CGContextScaleCTM(context, 1.0, -1.0);
// 创建绘制区域
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
//文字相关的属性都是由NSMutableAttributedString来设置的
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"爱笑的女孩运气不会太差,太差你倒是也笑不出来的"];
[att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(4, 5)];
[att addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(11, 4)];
[att addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:NSMakeRange(3, 4)];
//上下行的间距
CGFloat lineSpace = 30 ;
const CFIndex num = 1;
CTParagraphStyleSetting theSettings[num] = {
{kCTParagraphStyleSpecifierLineSpacingAdjustment,sizeof(CGFloat),&lineSpace},
};
CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, num);
// NSMakeRange(0, att.length) 整段文字长度
[att addAttribute:NSParagraphStyleAttributeName value:(__bridge id)(theParagraphRef) range:NSMakeRange(0, att.length)];
//排版
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString((CFAttributedStringRef)att);
CTFrameRef frame =
CTFramesetterCreateFrame(framesetter,
CFRangeMake(0, [att length]), path, NULL);
//绘制
CTFrameDraw(frame, context);
//释放
CFRelease(theParagraphRef);
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
}