用变换渲染UILabel

时间:2017-01-30 22:46:42

标签: objective-c iphone xcode uiimage uilabel

我已经旋转了UILabel(带变换的UILabel):centerLabel.transform = CGAffineTransformMakeRotation( ( 90 * M_PI ) / 180 );

我需要将我的UILabel渲染到UIImage中,但我不能用变换来实现它。当我渲染UILabel时,我没有变换就得到了UILabel。我该怎么做?

这是我的方法:

+ (UIImage *) imageWithView:(UIView *)view andOpaque:(BOOL)opaque {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}

1 个答案:

答案 0 :(得分:-1)

要从 UILabel 制作图像,请尝试以下代码:

#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CALayer.h>

旋转 UILabel

centerLabel.transform = CGAffineTransformMakeRotation( ( 90 * M_PI ) / 180 );

之后将捕获的图像存储在 UIImage

UIImage *image = [self imageWithView:centerLabel];

捕获的图像将无法旋转。如果要在旋转中使用该图像,则需要在捕获UILabel后对 UIImageView 使用 CGAffineTransformMakeRotation

- (UIImage *) imageWithView:(UIView *)view
{
    // Create a "canvas" (image context) to draw in.
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0);  // high res

    // Make the CALayer to draw in our "canvas".
    [[view layer] renderInContext: UIGraphicsGetCurrentContext()];

    // Fetch an UIImage of our "canvas".
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // Stop the "canvas" from accepting any input.
    UIGraphicsEndImageContext();

    // Return the image.
    return image;
}