//CTFontDrawGlyphs 与 CGContextShowGlyphsAtPoint 详解
//CGGlyph 为 CGFontIndex 只是fontindex并不是glyph的数据存储地址
//此方法获取fontSize时会crash
self.font = [UIFont systemFontOfSize:18];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL);
CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(font);
CGFontRef cgFont = CTFontCopyGraphicsFont(font,&ctFontDesRef );
CFNumberRef pointSizeRef = (CFNumberRef)CTFontDescriptorCopyAttribute(ctFontDesRef,kCTFontSizeAttribute);
CGFloat fontSize;
CFNumberGetValue(pointSizeRef, kCFNumberCGFloatType,&fontSize);
CGContextSetFontSize(context, fontSize);
//此方法获取fontSize时不会crash
//font = CTFontCreateWithName(CFSTR("ArialMT"), 20.0, NULL);
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL);
CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(font);
CGFontRef cgFont = CTFontCopyGraphicsFont(font,&ctFontDesRef );
CFNumberRef pointSizeRef = (CFNumberRef)CTFontDescriptorCopyAttribute(ctFontDesRef,kCTFontSizeAttribute);
CGFloat fontSize;
CFNumberGetValue(pointSizeRef, kCFNumberCGFloatType,&fontSize);
CGContextSetFontSize(context, fontSize);
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
//CTFontDrawGlyphs 与 CGContextShowGlyphsAtPoint 详解
NSUInteger length = self.text.length;
unichar chars[length];
CGGlyph glyphs[length];
self.font = [UIFont systemFontOfSize:18];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL);
[self.text getCharacters:chars range:NSMakeRange(0, length)];
CTFontGetGlyphsForCharacters(font, chars, glyphs, length);
//以下两种方法都可以绘制glyphs但是由于使用不用的坐标原点
//coretext的坐标原点在左下角
//coregraphic的坐标原点在左上角
//因此使用coretext和coregraphic绘制glyphs时坐标矩阵的处理是不同的
//另外使用CTFontDrawGlyphs函数绘制glyphs时需要保证CGPoint数组要和glyphs的数据个数保持一致
#if 1
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextStrokePath(context);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
const CGPoint points[] = {
20,30,
40,30,
60,30,
80,30,
};
const CGPoint * pointsPoint = points;
CTFontDrawGlyphs(font, glyphs, pointsPoint, 4, context);
#else
CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, textTransform);
CGContextStrokePath(context);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(font);
CGFontRef cgFont = CTFontCopyGraphicsFont(font,&ctFontDesRef );
CGContextSetFontSize(context, 20);
CGContextSetFont(context, cgFont);
//使用CGContextShowGlyphsAtPoint画glyphs时必须要设置字体和字体大小
CGContextShowGlyphsAtPoint(context, 0, 20, glyphs, 1);
#endif
CFRelease(font);
}