我正在尝试使用CoreText将一些文本写入我的子类NSView。这些字母相互叠加,字体太大。下面是我的drawRect方法的代码。知道我可能做错了吗?
编辑:Here is an image of the output.
- (void)drawRect:(NSRect)dirtyRect
{
NSGraphicsContext* contextRefNS = [NSGraphicsContext currentContext];
CGContextRef contextRef = (CGContextRef)[contextRefNS graphicsPort];
[[NSColor whiteColor] set];
NSRectFill([self bounds]);
CTFontRef fontRef;
CFStringRef fontNameRef;
fontNameRef = CFStringCreateWithCString(0, "Verdana", kCFStringEncodingASCII);
if (fontNameRef)
{
float fFontSize = 10.0f;
fontRef = CTFontCreateWithName(fontNameRef, fFontSize, 0);
CFRelease(fontNameRef);
}
CFStringRef stringRef = CFStringCreateWithCString(kCFAllocatorDefault, "TestText", kCFStringEncodingASCII);
if (stringRef && fontRef)
{
CGColorRef cgColorRef = CGColorCreateGenericRGB(0,0,0,1);
CFStringRef keys[] = { kCTFontAttributeName, kCTForegroundColorAttributeName };
CFTypeRef values[] = { fontRef, cgColorRef };
CFDictionaryRef attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&keys,(const void**)&values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
unsigned char bAntiAlias = 1;
CFAttributedStringRef attrStr = CFAttributedStringCreate(0, stringRef, attributes);
CFRelease (attributes);
if (attrStr)
{
CTLineRef line = CTLineCreateWithAttributedString(attrStr);
if (line)
{
if (bAntiAlias)
CGContextSetShouldAntialias(contextRef, true);
else
CGContextSetShouldAntialias(contextRef, false);
CGContextSetShouldSmoothFonts(contextRef, true);
CGContextSetTextPosition(contextRef, 100, 200);
CTLineDraw(line, contextRef);
CFRelease(line);
}
CFRelease(attrStr);
}
CFRelease(cgColorRef);
}
CFRelease(stringRef);
CFRelease(fontRef);
}