Drawing rotated text with NSString drawInRect

I solve this problem in next way.

1) Declare category on NSString

@interface NSString (NMSchemeItemDraw)
-(void)  drawWithBasePoint:(CGPoint)basePoint
                    andAngle:(CGFloat)angle
                     andFont:(UIFont*)font;
@end

This category will draw text with given central point, in one line and with given font and angle.

2) Implementation of this category is looks like:

@implementation NSString (NMSchemeItemDraw)

    -(void)  drawWithBasePoint:(CGPoint)basePoint
                     andAngle:(CGFloat)angle
                      andFont:(UIFont *)font{
    CGSize  textSize    =   [self   sizeWithFont:font];

    CGContextRef    context =   UIGraphicsGetCurrentContext();
    CGAffineTransform   t   =   CGAffineTransformMakeTranslation(basePoint.x, basePoint.y);
    CGAffineTransform   r   =   CGAffineTransformMakeRotation(angle);


    CGContextConcatCTM(context, t);
    CGContextConcatCTM(context, r);

    [self   drawAtPoint:CGPointMake(-1 * textSize.width / 2, -1 * textSize.height / 2)
               withFont:font];

    CGContextConcatCTM(context, CGAffineTransformInvert(r));
    CGContextConcatCTM(context, CGAffineTransformInvert(t));
    }
@end

3) Now i can use it in my [UIView drawRect:] method.
For example, in a next way:

 -(void)drawRect:(CGRect)rect{
 NSString* example = @"Title";
 [example drawWithBasePoint:CGPointMake(0.0f, 0.0f)
                   andAngle:M_PI
                    andFont:[UIFont boldSystemFontOfSize:16.0]];
 }

Leave a Comment