iOS 开发使用程序截图分享

本文介绍了在iOS设备上进行屏幕截图的方法,包括截取全屏图片、指定View的图片及自定义大小区域的图片,并提供了完整的代码实现。

在做项目的时候经常遇到需要截取屏幕上面的图片来进行第三方分享操作,下面就来介绍怎么使用截图。

1.截取设备的全屏图片代码如下:

 1 - (void)fullScreenShots
 2 {
 3     UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
 4     UIGraphicsBeginImageContext(screenWindow.frame.size);//全屏截图,包括window
 5     [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
 6     
 7     UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
 8     UIGraphicsEndImageContext();
 9     
10     UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);   //保存到相册中
11 }

2.截取指定View上展示的图片

 1 - (void)save
 2 {
 3     UIGraphicsBeginImageContext(mybackgroundview.bounds.size); //currentView 当前的view
 4     [mybackgroundview.layer renderInContext:UIGraphicsGetCurrentContext()];
 5     
 6     UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
 7     UIGraphicsEndImageContext();
 8     
 9     UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);   //保存到相册中
10 }

3.截取自定义大小(CGRect)区域的图片

 1 - (void)saveCustomRect
 2 {
 3     UIGraphicsBeginImageContext(CGSizeMake(320, 300)); //设置截屏区域
 4     [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
 5     
 6     UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
 7     UIGraphicsEndImageContext();
 8     
 9     UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);  //保存到相册中
10 }

 

以上方法基本上能满足截取当前屏幕所显示的图片用来分享的需求了。下面给出一套整体的截图代码:

 1 //获得屏幕图像
 2 - (UIImage *)imageFromView:(UIView *)view
 3 {
 4     UIGraphicsBeginImageContext(view.frame.size);
 5     CGContextRef context = UIGraphicsGetCurrentContext();
 6     [view.layer renderInContext:context];
 7     
 8     UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
 9     UIGraphicsEndImageContext();
10     
11     return theImage;
12 }
13 
14 //获得某个范围内的屏幕图像
15 - (UIImage *)imageFromView:(UIView *)view atFrame:(CGRect)rect
16 {
17     UIGraphicsBeginImageContext(view.frame.size);
18     CGContextRef context = UIGraphicsGetCurrentContext();
19     CGContextSaveGState(context);
20     UIRectClip(rect);
21     [view.layer renderInContext:context];
22     
23     UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
24     UIGraphicsEndImageContext();
25     
26     return theImage;
27 }

 

 

转载于:https://www.cnblogs.com/shixiong-luo/p/iOS-Graphics-Image.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值