iPhone에서 작동하는 다음 샘플 코드가 있습니다. 텍스트 "Hello World!"를 그립니다. 핵심 텍스트를 사용하여 화면에.코코아 응용 프로그램의 코어 텍스트
NSView에서이 코드를 코코아 프로젝트에 드롭하면 다른 결과가 나타납니다. 글꼴 크기가 훨씬 더 크게 조정되고 글자가 서로 위에 그려집니다. 어떻게 코코아 응용 프로그램에서 텍스트를 그릴 수 있습니까?
- (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의 (예상 결과)에
NSView의 (예기치 않은 결과)에있는 맥 @ 매트는,이 지적했듯이
Mac OS X Cocoa에서는 UIGraphicsGetCurrentContext()가 존재하지 않으므로이 코드는 실제 코드가 될 수 없습니다. – matt
Mac OS X에서도 이미 플립되었습니다. 플립 코드를 제거해야합니다. – matt
mac 버전은 그래픽 컨텍스트에 대해 [[NSGraphicsContext currentContext] graphicsPort]를 사용하지만 그렇지 않은 경우 스크린 샷에 사용되는 것과 동일한 코드입니다. –