iOS 开发使用程序截图分享

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

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 }

 

 

posted @ 2014-05-18 14:27  心中的空白之地  阅读(1282)  评论(0)    收藏  举报