如何旋转String并将此String保存为swift中的UIImage

时间:2015-06-29 05:45:43

标签: ios swift uiimage cgaffinetransform uigraphicscontext

我需要旋转String并将此旋转字符串另存为UIImage

假设我的给定字符串= HELLO WORLD

现在我需要首先旋转(比如45度)而不是保存为UIImage所以我可以将UIImage显示在我的UIImageView

请帮帮我。所以我可以旋转String并将此旋转字符串保存为Swift中的UIImage

我找到了这个答案Drawing rotated text with NSString drawInRect。但无法达到效果。

1 个答案:

答案 0 :(得分:0)

可能是下面的代码帮助你,我在45度旋转字符串时取得了相同的结果

-(UIImage*) drawText:(NSString*) text
         atPoint:(CGPoint)   point
{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(65, 65),NO,0.0);

CGRect rect = CGRectMake(point.x, point.y, 50, 30);
[[UIColor whiteColor] set];
CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeTranslation(32.5, 32.5));
CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeRotation(M_PI / 4));
CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeTranslation(-32.5, -32.5));
//[text drawInRect:CGRectIntegral(rect) withFont:font ];

NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
NSDictionary *attributes = @{ NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:12],
                              NSForegroundColorAttributeName: [UIColor blackColor],

                              NSParagraphStyleAttributeName:paragraphStyle};

[text drawInRect:CGRectIntegral(rect) withAttributes:attributes];


UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return newImage;
}

下面是我获得结果enter image description here

的屏幕截图