iOS 指定的 UIView 生成 UIImage

Posted by Calvin on 2017-04-21

部分产品可能会有分享功能,而且分享的是某个 UIView,曾经尝试过用户点击分享后对页面进行截屏然后分享,但是发现截屏存在很多的缺陷。

后来在使用水滴清单的过程中,发现它的打卡功能分享出去也是一张图片,但图片不是简单的截屏,而是生成的图片再进行分享。接下来就用 UIView 生成一张 UIImage。

1、创建要分享的视图

创建要分享的视图并在视图上布局对应的控件,为了方便,我只放一张图片和一句话在 UIView 上并生成图片,代码:

- (void)createShareView{
self.shareView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height+20)];
self.shareView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1];
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, [UIScreen mainScreen].bounds.size.width-40, [UIScreen mainScreen].bounds.size.height-60)];
image.image = [UIImage imageNamed:@"huaban.jpeg"];
[self.shareView addSubview:image];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, image.bounds.size.height+30, [UIScreen mainScreen].bounds.size.width-20, 30)];
label.text = @"Stay hungry Stay foolish.";
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor lightGrayColor];
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont systemFontOfSize:18];
[self.shareView addSubview:label];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 200, [UIScreen mainScreen].bounds.size.width-40, 44)];
btn.backgroundColor = [UIColor redColor];
btn.layer.cornerRadius = 5;
btn.layer.masksToBounds = YES;
[btn setTitle:@"Share" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(BtnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}

创建分享视图 ShareView 并放上一张图片,一句话。点击按钮时再进行生成图片。

UIView 生成 UIImage

用户点击按钮进行图片的生成,生成后保存在本地

- (void)BtnClicked
{
UIImage *img = [self createViewImage:self.shareView];
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

UIView 生成 UIImage 代码方法:

- (UIImage *)createViewImage:(UIView *)shareView {
UIGraphicsBeginImageContextWithOptions(shareView.bounds.size, NO, [UIScreen mainScreen].scale);
[shareView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

效果如下:
20170421149275886595354.jpg

因为我的手机是 iPhone 6s,所以生成的尺寸是 750x1374。当然图片的大小和内容是根据代码进行设置的。

生成图片以后进行分享或者保存就很随意了。

『 Demo 下载 』