这是一个UIImage
从视图(包括它的子视图)创建的方法。假设图像在 a 中,在 aUIImageView
中添加用户文本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 基础添加到您的项目并添加
#import <QuartzCore/QuartzCore.h>
到您的 .m 文件中。
这是 a 中适用的代码,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;
}
以及 s的输出NSLog
:
2013-06-28 15:57:13.052 SOSandbox[28772:907] Source image size: 1213 x 1159
2013-06-28 15:57:13.055 SOSandbox[28772:907] onScreenImageView size: 200 x 200
2013-06-28 15:57:14.963 SOSandbox[28772:907] offScreenImageView size: 1213 x 1159
2013-06-28 15:57:14.992 SOSandbox[28772:907] Labeled image size: 1213 x 1159