2013-10-27 20 views
6

CGContextSelectFont và CGContextShowTextAtPoint không được chấp nhận trong iOS 7. Tương đương trong C là gì?CGContextSelectFont và CGContextShowTextAtPoint trong iOS 7

Tất cả các câu trả lời tôi đã nhìn thấy tương đương Objective-C (như sử dụng phương pháp NSString) nhưng tôi đang làm việc trong các tệp C++.

+0

Bạn đã bao giờ tìm thấy điều này? – newenglander

Trả lời

6

Đây là giải pháp. Các chức năng này đã không còn được sử dụng để ủng hộ cho Core Text. Nó nâng cao hơn nhiều nhưng phải mất một lúc để tìm ra. Mẫu này rút ra "Hello World!" sử dụng phông chữ Courier.

- (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); 
} 

enter image description here

Các vấn đề liên quan