如何在iPhone上旋转Quartz绘制的文本

时间:2009-12-14 09:01:07

标签: iphone objective-c text rotation quartz-graphics

我想用Quartz绘制一些文本。现在应用程序绘制 alt text ,但我希望它显示为“0123456789”。有没有办法显示它的正常方向?

这是我的代码:

    //set image view
 drawImage = [[UIImageView alloc] initWithImage:nil];
 drawImage.frame = self.view.frame;
 [self.view addSubview:drawImage];

 UIGraphicsBeginImageContext(self.view.frame.size);  // begin
 // current context
 CGContextRef context = UIGraphicsGetCurrentContext();

 CGContextSelectFont(context, "Courier", 40,  kCGEncodingMacRoman);
 CGFloat white[] = {1.0, 1.0, 1.0, 1.0};
 CGContextSetFillColor(context, white);
 CGContextShowTextAtPoint(context, 0, 30, "0123456789", strlen("0123456789"));

 // get image
 drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();    // end

4 个答案:

答案 0 :(得分:14)

在Quartz中,图像会颠倒,因为它的Y轴是倒置的。

iPhone的Y轴从上到下变为正,即原点位于左上角,而在Quartz和OpenGL中,坐标与良好的旧几何形状(即左下角的原点)相同。

以下是解决Quartz反演问题的一些代码:

CGContextRef ctx = UIGraphicsGetCurrentContext();
// Tanslate and scale upside-down to compensate for Quartz's inverted coordinate system
CGContextTranslateCTM(ctx, 0.0, rect.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

这是一篇有趣的帖子,作者说新加坡的一个团队因为这个倒置问题放弃了一个iPhone项目,他们无法弄清楚:http://trandangkhoa.blogspot.com/2009/07/iphone-os-drawing-image-and-stupid.html

答案 1 :(得分:4)

另一种处理方法是将Quartz文本绘图代码(从CGSelectFont()替换为CGContextShowTextAtPoint()),例如

[text drawAtPoint:CGPointMake(0.0f, 30.0f) withFont:[UIFont fontWithName:@"Courier" size:40.0f]];

其中text是NSString。在iPhone上,-drawAtPoint:withFont:自动翻转文本以考虑UIViews的反转Y轴。

这种方法使您可以处理比纯Quartz文本绘图中的MacRoman编码更宽泛的字符集。但是,它稍慢。

答案 2 :(得分:0)

“将它们旋转到正常模式”是什么意思?

假设您只是意味着在2D空间内旋转,您通常会使用变换矩阵。看看CGAffineTransformMakeRotation

您可以将它应用于视图本身(通过设置transform属性),或者应用于您拥有的CG上下文。

答案 3 :(得分:0)

这解决了我的问题

CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));