2013-12-10 43 views
0

如何將NSString旋轉到某種程度?當我畫一個字符串與圖像。如何在CGContext中旋轉NSString drawinrect

我提到這個SO問題Drawing rotated text with NSString drawInRect但我的橢圓已經消失了。

//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; 
} 
+1

請不要前綴'kCG'您的自定義變量。它們不是Core Graphics的一部分。 –

+0

我沒有看到任何代碼轉換上下文(即旋轉它)。你確定那部分工作正常嗎? –

+0

@DavidRönnqvist我添加了我用來旋轉字符串的那一行。我的文字會消失,一旦我添加3行 – Desmond

回答

5

CGAffineTransformMakeRotation將圍繞上下文的原點旋轉(在此情況下,x = 0,Y = 0)。

要正確旋轉文字,您需要首先將上下文的原點與包含該字符串的框的中心進行平移,然後旋轉並將原點移回其原始位置。

更換3條線路在您使用應用旋轉:

CGContextConcatCTM(context, CGAffineTransformMakeTranslation(18, 18)); 
CGContextConcatCTM(context, CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(65))); 
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-18, -18)); 
+0

感謝您的答案。三條線就像魅力! – Desmond