2009-08-09 41 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);