這裏有一個方法,將從視圖(包括它的子視圖)創建一個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基礎添加到您的項目,並將 #import <QuartzCore/QuartzCore.h>
添加到您的.m文件。
以下是在一個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
S上的輸出:
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
在我問這個問題之前,我剛纔在Apple的文檔中閱讀了這個。我將如何創建一個圖像,這是從相機捕獲的圖像的實際尺寸?這讓我感到困惑,因爲這最終會在手機上創造一些非常小的東西,不是嗎? – Rob
或者我誤解了這種方法如何處理數據/圖像捕獲? – Rob
您傳入的視圖不需要位於設備的屏幕上,因此您可以創建例如尺寸與源圖像相同的「UIImageView」。然後添加你的'UILabel'作爲子視圖。在用戶指示應該保存標記的圖像之後,執行此操作。 – bobnoble