iphone - 在 CGContext 中翻转 NSString 绘图

标签 iphone

我尝试在此纹理中绘制字符串:

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:对不起我的英语;)

最佳答案

如描述here ,与正常的 Quartz 绘图空间相比,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);

这是一个相当粗略的示例,因为我相信它只是在图像底部绘制文本,但您应该能够调整文本的翻译或坐标以将其放置在需要的位置。

关于iphone - 在 CGContext 中翻转 NSString 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252343/

相关文章:

iphone - 在 UICollectionViewCell 中添加分隔符,就像在 UITableViewCell 中添加分隔符一样

iphone - 将 tableView 交换到 UITableViewController 中的另一个 View

iphone - 填充 UILabel 文本而不链接 IBOutlet

iphone - 音频压缩不适用于 iTunes 歌曲

iphone - 从子类访问父类的实例变量

javascript - jQuery 适用于 Chrome、Firefox、IE 但不适用于 iPhone

ios - Xcode 看不到变量

iphone - 请解释这可能是如何泄漏的 - 字符串编码函数

iphone - sqlite 文件已加密或不是数据库 iPhone sms.db

iphone - 如何从 NSDate 对象获取字符串以来的时间?