为什么我的文字自下而上?

时间:2011-03-24 19:50:33

标签: ios objective-c core-text

在我的自定义视图中,我有以下代码:

-(void) drawRect:(CGRect) rect
{
    // Drawing code   
    CGContextRef context = UIGraphicsGetCurrentContext();

    ![NSString *myString = @"Hello World, This is for\nhttp://www.stackoverflow.com";
    // Prepare font
    CTFontRef font = CTFontCreateWithName(CFSTR("Times"), 12, NULL);

    // Create an attributed string
    CFStringRef keys[] = { kCTFontAttributeName };
    CFTypeRef values[] = { font };
    CFDictionaryRef attr = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values,
                                              sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFAttributedStringRef attrString = CFAttributedStringCreate(NULL, (CFStringRef)myString, attr);
    CFRelease(attr);

    // Draw the string
    //CTLineRef line = CTLineCreateWithAttributedString(attrString);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.frame);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
    //CGContextSetTextMatrix(context, CGAffineTransformIdentity); // this line is wrong,  use the below line
    CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, -1.0)); 
    CGContextSetTextPosition(context, 20, 12);
    CTFrameDraw(frame, context);

    // Clean up
    CFRelease(path);
    CFRelease(frame);
    CFRelease(attrString);
    CFRelease(font);
}

然而,看起来像这样:

http://i.stack.imgur.com/iGonN.png

如何让文字记录下来,并从左上角开始?

1 个答案:

答案 0 :(得分:9)

这是副本&粘贴我的一个drawRect:方法,它可以很好地工作。

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState( ctx );

CGContextSetTextMatrix( ctx, CGAffineTransformIdentity );

CGContextTranslateCTM( ctx, rect.origin.x, rect.origin.y );
CGContextScaleCTM( ctx, 1.0f, -1.0f );
CGContextTranslateCTM( ctx, rect.origin.x, - ( rect.origin.y + rect.size.height ) );

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect( path, NULL, rect );

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString( __labelData.attributedString );  
CTFrameRef frame = CTFramesetterCreateFrame( framesetter, CFRangeMake( 0, 0 ), path, NULL );    

CTFrameDraw( frame, ctx );

CGPathRelease( path );  
CFRelease( frame );
CFRelease( framesetter );

CGContextRestoreGState( ctx );  

只需将__labelData.attributedString替换为您的属性字符串。