坐標(biāo)系
如果你了解過 iOS UIKit袒餐,你就知道坐標(biāo)的原點(diǎn)就在屏幕的左上角飞蛹,但是底層Core Graphics的context使用的坐標(biāo)系的原點(diǎn)是在屏幕的左下角。那從底層到上層一定是做了轉(zhuǎn)變灸眼。蘋果官方例圖
上圖可以看到卧檐,坐標(biāo)系發(fā)生了改變,變成了我們最熟悉的模樣焰宣。具體代碼實(shí)現(xiàn)如下:
- (void)drawRect:(CGRect)rect{
[super drawRect:rect];
//獲得當(dāng)前的Graphics Context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
//向上平移一個視圖高度的距離
CGContextTranslateCTM(context, 0, self.bounds.size.height);
//圍繞x軸的翻轉(zhuǎn)
CGContextScaleCTM(context, 1.0, -1.0);
}
寫一小段文字效果:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
//獲得當(dāng)前的Graphics Context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
//向上平移一個視圖高度的距離
CGContextTranslateCTM(context, 0, self.bounds.size.height);
//圍繞x軸的翻轉(zhuǎn)
CGContextScaleCTM(context, 1.0, -1.0);
// 創(chuàng)建繪制區(qū)域
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
//文字相關(guān)的屬性都是由NSMutableAttributedString來設(shè)置的
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"愛笑的女孩運(yùn)氣不會太差霉囚,太差你倒是也笑不出來的"];
[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);
}