2009-08-09 42 views
3

畫我試着在此紋理繪製字符串:翻轉的NSString在CGContext上

http://picasaweb.google.it/lh/photo/LkYWBv_S_9v2d6BAfbrhag?feat=directlink

但是綠色的數字似乎垂直翻轉。 我已經建立了我這樣背景:

colorSpace = CGColorSpaceCreateDeviceRGB(); 
data = malloc(height * width * 4); 
context = CGBitmapContextCreate(data, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 

,我已經繪製字符串:

UIGraphicsPushContext(context); 

for(int i=0;i<packs.size();++i) 
{ 
    CGPoint points[4] = 
    { 
     gltextures[i].texCoords[0] * size.width,  //0 
     gltextures[i].texCoords[1] * size.height,  //1 

     gltextures[i].texCoords[2] * size.width,  //2 
     gltextures[i].texCoords[3] * size.height,  //3 

     gltextures[i].texCoords[4] * size.width,  //4 
     gltextures[i].texCoords[5] * size.height,  //5 

     gltextures[i].texCoords[6] * size.width,  //6 
     gltextures[i].texCoords[7] * size.height  //7 

    }; 

    CGRect debugRect = CGRectMake 
    (
    gltextures[i].texCoords[0] * size.width, 
    gltextures[i].texCoords[1] * size.height, 
    gltextures[i].width, 
    gltextures[i].height 
    ); 
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]); 
    CGContextAddLines(context, points, 4); 
    CGContextClosePath(context); 
    CGContextDrawPath(context, kCGPathStroke); 

    NSString* s = [NSString stringWithFormat:@"%d",gltextures[i].texID]; 
    UIFont* font = [UIFont fontWithName:@"Arial" size:12]; 
    CGContextSetRGBFillColor(context, 0, 1, 0, 1); 
    [s drawAtPoint:points[0] withFont:font]; 
} 
UIGraphicsPopContext(); 

變換矩陣似乎身份矩陣...沒有CGAffineTransform應用於此背景下。 如果字符串翻轉,也許,我的所有圖像翻轉! 有什麼建議嗎?

PS:抱歉,我的英語)

回答

7

作爲描述here,座標系統的上下文一個UIView內或相比於正常石英繪製空間時,其層被反轉。但是,當使用Quartz繪製圖像時,情況不再一樣。 NSString上的UIStringDrawing Cocoa Touch類別爲您提供了-drawAtPoint:withFont:方法,它假定了一個反轉的佈局,這就是爲什麼您會看到圖像中的翻轉文本。

解決此問題的一種方法是保存圖形狀態,對圖像應用反轉轉換,繪製文本並還原舊圖形狀態。這看起來像下面這樣:

CGContextSaveGState(context); 
CGContextTranslateCTM(context, 0.0f, self.bounds.size.height); 
CGContextScaleCTM(context, 1.0f, -1.0f); 

[text drawAtPoint:CGPointMake(0.0f, 0.0f) withFont:font]; 

CGContextRestoreGState(context); 

這是一個相當原始的例子,因爲我相信這只是繪製在圖像底部的文字,但你應該能夠調整翻譯或座標將文本放置在需要的地方。

2

更好的保存抽籤之前的文本的矩陣,否則會被CoreGraphic影響其他文本抽獎:

CGContextSaveGState(ctx); 
CGAffineTransform save = CGContextGetTextMatrix(ctx); 
CGContextTranslateCTM(ctx, 0.0f, self.bounds.size.height); 
CGContextScaleCTM(ctx, 1.0f, -1.0f); 
[str drawAtPoint:point withFont:font]; 
CGContextSetTextMatrix(ctx, save); 
CGContextRestoreGState(ctx);