[英]Core Text in Cocoa app
我有以下示例代码适用于iPhone。 它绘制了文本“Hello World!” 在屏幕上使用Core Text。
将此代码放入NSView中的cocoa项目会产生不同的结果。 字体大小缩放得更大,字母相互重叠。 如何在cocoa应用程序中绘制相同的文本?
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CFStringRef font_name = CFStringCreateWithCString(NULL, "Courier", kCFStringEncodingMacRoman);
CTFontRef font = CTFontCreateWithName(font_name, 36.0, NULL);
CFStringRef keys[] = { kCTFontAttributeName };
CFTypeRef values[] = { font };
CFDictionaryRef font_attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&keys, (const void **)&values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFRelease(font_name);
CFRelease(font);
int x = 10;
int y = 10;
const char *text = "Hello World!";
CFStringRef string = CFStringCreateWithCString(NULL, text, kCFStringEncodingMacRoman);
CFAttributedStringRef attr_string = CFAttributedStringCreate(NULL, string, font_attributes);
CTLineRef line = CTLineCreateWithAttributedString(attr_string);
CGContextSetTextPosition(context, x, y);
// Core Text uses a reference coordinate system with the origin on the bottom-left
// flip the coordinate system before drawing or the text will appear upside down
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTLineDraw(line, context);
CFRelease(line);
CFRelease(string);
CFRelease(attr_string);
CGContextRestoreGState(context);
}
UIView中的iPhone(预期结果)
NSView中的Mac(意外结果)
正如@matt所指出的,这不是Cocoa代码,坐标系的起源是Cocoa上的“左下角”,而UIGraphicsGetCurrentContext()
不存在......
无论如何,您需要将上下文的文本矩阵至少设置为CGAffineTransformIdentity
。 但由于CGContextSetTextPosition
未设置CTDrawLine
的位置, CTDrawLine
需要将文本矩阵转换为所需位置。
- (void)drawRect:(NSRect)dirtyRect
{
CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(context);
CFStringRef font_name = CFStringCreateWithCString(NULL, "Courier", kCFStringEncodingMacRoman);
CTFontRef font = CTFontCreateWithName(font_name, 36.0, NULL);
CFStringRef keys[] = { kCTFontAttributeName };
CFTypeRef values[] = { font };
CFDictionaryRef font_attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&keys, (const void **)&values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFRelease(font_name);
CFRelease(font);
int x = 10;
int y = 10;
CFAttributedStringRef attr_string = CFAttributedStringCreate(NULL, CFSTR("Hello World!"), font_attributes);
CTLineRef line = CTLineCreateWithAttributedString(attr_string);
// You need to set the text matrix at least to CGAffineTransformIdentity
// Here we translate to the desired position
CGContextSetTextMatrix(context, CGAffineTransformMakeTranslation(x,y));
CTLineDraw(line, context);
CFRelease(line);
CFRelease(attr_string);
CGContextRestoreGState(context);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.