2011-03-24 49 views
3

在我的自定義視圖,我有以下代碼:爲什麼我的文字從下往上畫?

-(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

我怎樣才能讓文字下去,也從一開始左上方?

回答

8

下面是我的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即可。

+0

非常感謝'SO'!我把頭髮拉過這個,它完美的工作! – 2011-03-24 21:25:31