在图像上渲染文本,以全分辨率保存图像?

时间:2013-06-28 17:09:32

标签: ios objective-c uiimage uikit

我需要为图像添加文本标签,然后让用户能够保存带有文本的图像。问题是,我找不到任何关于如何做到这一点的好信息。标志指向使用UIKit的UIGraphicsBeginImageContextUIGraphicsGetImageFromCurrentImageContextUIGraphicsEndImageContext。我甚至不确定这是否是正确的方向。我需要在保存图像时不缩小图像。他们必须保持决心。

我很茫然。关于在哪里寻找或下一步尝试的任何建议或帮助都会非常有帮助。

1 个答案:

答案 0 :(得分:2)

这是一种从视图中创建UIImage的方法(包括它的子视图)。假设图片位于UIImageView,请将UILabel中的用户文字添加为UIImageView的子视图。

+(UIImage *)imageFromView:(UIView *)view{

    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext

    CGSize imageSize = view.bounds.size;
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);

    CGContextRef context = UIGraphicsGetCurrentContext();

    [view.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    return image;
}

目前,它使用视图的大小作为图像的大小。如果您希望它的大小不同,那么您可以传递所需大小的结果图像并根据需要设置imageSize

您需要将QuartzCore基础添加到项目中并添加 {。}}到您的.m文件。

以下是#import <QuartzCore/QuartzCore.h>中适用的代码,用于将生成的图像调整为源图像的大小,其中大部分采用UIViewController方法:

saveButtonTapped

来自- (void)viewDidLoad { [super viewDidLoad]; sourceImage = [UIImage imageNamed:@"animal"]; self.onScreenImageView.image = sourceImage; } -(void)viewWillAppear:(BOOL)animated{ NSLog(@"Source image size: %0.0f x %0.0f", sourceImage.size.width, sourceImage.size.height); NSLog(@"onScreenImageView size: %0.0f x %0.0f", self.onScreenImageView.frame.size.width, self.onScreenImageView.frame.size.height); } - (IBAction)saveButtonTapped:(id)sender { UIImageView *offScreenImageView = [[UIImageView alloc] initWithImage:sourceImage]; NSLog(@"offScreenImageView size: %0.0f x %0.0f", offScreenImageView.frame.size.width, offScreenImageView.frame.size.height); UILabel *offScreenLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 1000, 100)]; offScreenLabel.font = [UIFont systemFontOfSize:80.f]; offScreenLabel.textColor = [UIColor blackColor]; offScreenLabel.text = @"User Image Label Text"; [offScreenImageView addSubview:offScreenLabel]; UIImage *labeledImage = [NAHLabelPictureVC imageFromView:offScreenImageView]; NSLog(@"Labeled image size: %0.0f x %0.0f", labeledImage.size.width, labeledImage.size.height); self.labeledImageView.image = labeledImage; } 的输出:

NSLog