iPhone:绘制旋转文字?

s4y*_*s4y 6 iphone drawing text rotation

我想在视图中绘制一些文本,旋转90°.我对iPhone开发很陌生,而且在网络上发布了许多不同的解决方案.我已经尝试了一些,通常最终我的文字被修剪.

这里发生了什么?我正在一个相当小的空间(一个表格视图单元格)中画画,但是必须采用"正确"的方式来做到这一点......对吗?


编辑:以下是几个例子.我正试图在左边的黑条上显示文字" 12345 ".

  1. 第一次尝试,来自RJShearman的Apple Discussions

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSelectFont (context, "Helvetica-Bold", 16.0, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode (context, kCGTextFill);
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetTextMatrix (context, CGAffineTransformRotate(CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f ), M_PI/2));
    CGContextShowTextAtPoint (context, 21.0, 55.0, [_cell.number cStringUsingEncoding:NSUTF8StringEncoding], [_cell.number length]);
    CGContextRestoreGState(context);
    
    Run Code Online (Sandbox Code Playgroud)

    尝试一个.这两个中的一个和一部分被剪掉了.http://dev.deeptechinc.com/sidney/share/iphonerotation/attempt1.png

  2. 第二次尝试,来自zgombosi的iPhone Dev SDK.相同的结果(这里的字体略小,因此剪裁较少).

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPoint point = CGPointMake(6.0, 50.0);
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, point.x, point.y);
    CGAffineTransform textTransform = CGAffineTransformMakeRotation(-1.57);
    CGContextConcatCTM(context, textTransform);
    CGContextTranslateCTM(context, -point.x, -point.y);
    [[UIColor redColor] set];
    [_cell.number drawAtPoint:point withFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]];
    CGContextRestoreGState(context);
    
    Run Code Online (Sandbox Code Playgroud)

    尝试两个.有几乎相同的剪辑http://dev.deeptechinc.com/sidney/share/iphonerotation/attempt2.png

s4y*_*s4y 7

事实证明,无论行高如何,我的表格单元格总是被初始化为44px高,因此我的所有绘图都被从单元格的顶部剪切了44px.

为了吸引更大的单元格,设置的内容视图的,有必要autoresizingMask

cellContentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Run Code Online (Sandbox Code Playgroud)

要么

cellContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
Run Code Online (Sandbox Code Playgroud)

...并drawRect以正确的大小调用.在某种程度上,这是有道理的,因为UITableViewCellinitWithStyle:reuseIdentifier:只字不提细胞的大小,只有表视图实际上知道每行有多大将是,根据自己的规模和它的代表对响应tableView:heightForRowAtIndexPath:.

我阅读了Quartz 2D Programming Guide,直到绘图模型和函数开始有意义,并且绘制旋转文本的代码变得简单明了:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextRotateCTM(context, -(M_PI/2));
[_cell.number drawAtPoint:CGPointMake(-57.0, 5.5) withFont:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]];
CGContextRestoreGState(context);
Run Code Online (Sandbox Code Playgroud)

感谢您的提示,看起来我已经准备好了.