문제

how do i rotate a NSString to a certain degree ? when i draw a string together with an image.

i referred this SO question Drawing rotated text with NSString drawInRect but my Ellipse is gone.

//Add text to UIImage
-(UIImage *)addMoodFound:(int)moodFoundCount andMoodColor:(CGColorRef)mColour
{
    float scaleFactor = [[UIScreen mainScreen] scale];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), NO,scaleFactor);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    //CGContextSetRGBFillColor(context, kCGAggressiveColor);
    CGContextSetFillColorWithColor(context,mColour);
    CGContextFillEllipseInRect(context, CGRectMake(0, 0, 36, 36));
    CGContextSetRGBFillColor(context, 250, 250, 250, 1);

//nsstring missing after adding this 3 line
 CGAffineTransform transform1 = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(65));
    CGContextConcatCTM(context, transform1);
    CGContextTranslateCTM(context, 36, 0);

////////////////////////////////////////////////

    [[NSString stringWithFormat:@"%d",moodFoundCount ] drawInRect : CGRectMake(0, 7, 36, 18)
             withFont : [UIFont fontWithName:monR size:17]
        lineBreakMode : NSLineBreakByTruncatingTail
            alignment : NSTextAlignmentCenter ];

    CGContextRestoreGState(context);

    UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return theImage;
}
도움이 되었습니까?

해결책

CGAffineTransformMakeRotation will rotate around the context's origin (in this case x = 0, y = 0).

To properly rotate your text you need to first translate the origin of the context with the center of the box containing the string, rotate and move back the origin to its original location.

Replace the 3 lines where you're applying the rotation with:

CGContextConcatCTM(context, CGAffineTransformMakeTranslation(18, 18));
CGContextConcatCTM(context, CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(65)));
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-18, -18));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top