Drawing rotated text with NSString drawInRect

前端 未结 5 1845
借酒劲吻你
借酒劲吻你 2020-11-29 04:09

I found this answer on how to draw rotated text with NSString drawInRect:, but I\'m not sure how it works since it only sort of works for me: https://discussions.apple.com/t

5条回答
  •  时光取名叫无心
    2020-11-29 04:56

    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]];
     }
    

提交回复
热议问题