Rotating a NSString in drawRect

2019-08-30 23:33发布

I want to rotate my NSString that's at a set location so that it reads from bottom to up.

I know the issue lies in the CGContextTranslateCTM, but I'm not sure how to fix it. If I comment this line, I see my text where I want it, just not rotated. This must be moving my NSString to where it is not visible.

Thoughts?

Here's what I have tried:

NSString * xString = [NSString stringWithFormat:@"%@", self.xStringValue];
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor blackColor] CGColor]);
CGContextSaveGState(UIGraphicsGetCurrentContext());
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 0);
CGContextRotateCTM(UIGraphicsGetCurrentContext(), M_PI/2);
[xString drawInRect:(CGRectMake(x, y, width, height) withFont:self.Font];
CGContextRestoreGState(UIGraphicsGetCurrentContext());

EDIT:

The code above is drawing my NSString values, but they are being positioned off screen where I can not see them.

This code is actually getting them on screen, just not in the right place.

X and Y are both calculated distances.

- (void)drawRect:(CGRect)rect
{
     CGContextRef context = UIGraphicsGetCurrentContext();
     CGContextSaveGState(context);
     CGAffineTransform transform = CGAffineTransformMakeRotation(-90.0 * M_PI/180.0);
     CGContextConcatCTM(context, transform);
     CGContextTranslateCTM(context, -rect.size.height-x, rect.size.height-y);
     CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor blackColor] CGColor]);
     [xString drawInRect:CGRectMake(x, y, w, h) withFont:self.textFont];
     CGContextRestoreGState(context);
}

EDIT THREE:

Solution:

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, point.x, point.y);
    CGAffineTransform textTransform = CGAffineTransformMakeRotation(-1.57);
    CGContextConcatCTM(context, textTransform);
    CGContextTranslateCTM(context, -point.x, -point.y);
    CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor whiteColor] CGColor]);
    [string drawInRect:CGRectMake(x, y, width, height) withFont:font];
    CGContextRestoreGState(context);

1条回答
Deceive 欺骗
2楼-- · 2019-08-30 23:46

If you want to rotate a UILabel vertically (90°) you can do :

[_myLabel setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];

The result for a UILabel :

enter image description here

查看更多
登录 后发表回答