2011-03-24 4 views
3

À mon avis personnalisé, je le code suivant:Pourquoi mon texte est-il dessiné de bas en haut?

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

Cependant, qui ressemble à ceci:

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

Comment puis-je faire le texte aller vers le bas, et aussi commencer à partir de la en haut à gauche?

Répondre

8

Voici la copie & de l'une de mes méthodes drawRect:, qui fonctionne parfaitement.

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

Il suffit de remplacer __labelData.attributedString avec votre chaîne attribuée.

+0

Merci beaucoup! Je tirais mes cheveux par-dessus celui-ci, ça marche parfaitement! –