截屏 或 截取某个view的界面(给view拍照)

来源:互联网 发布:java hashcode 源码 编辑:程序博客网 时间:2024/06/08 20:00

基本原理就是主要将UIView的layer描绘到图形上下文。UIView全局拍照和局域拍照的代码如下:

1 UIView全局拍照

[cpp] view plaincopy
  1. - (UIImage *) screenImage:(UIView *)view {  
  2. UIImage *screenImage;  
  3. UIGraphicsBeginImageContext(view.frame.size);  
  4. [view.layer renderInContext:UIGraphicsGetCurrentContext()];  
  5. screenImage = UIGraphicsGetImageFromCurrentImageContext();  
  6. UIGraphicsEndImageContext();  
  7. return screenImage;  
  8. }  

2 UIView局域拍照

[cpp] view plaincopy
  1. - (UIImage *) screenImage:(UIView *)view rect:(CGRect)rect {  
  2. CGPoint pt = rect.origin;  
  3. UIImage *screenImage;  
  4. UIGraphicsBeginImageContext(rect.size);  
  5. CGContextRef context = UIGraphicsGetCurrentContext();  
  6. CGContextConcatCTM(context,  
  7. CGAffineTransformMakeTranslation(-(int)pt.x, -(int)pt.y));  
  8. [view.layer renderInContext:context];  
  9. screenImage = UIGraphicsGetImageFromCurrentImageContext();  
  10. UIGraphicsEndImageContext();  
  11. return screenImage;  
  12. }  

截屏

[cpp] view plaincopy
  1. UIGraphicsBeginImageContext(self.window.bounds.size);  
  2. [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];  
  3. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
  4. UIGraphicsEndImageContext();  


保存为图片

[cpp] view plaincopy
  1. NSData * data = UIImagePNGRepresentation(image);  
  2.   
  3.     if ([UIImagePNGRepresentation(viewImage) writeToFile:path atomically:YES])  
  4.     {  
  5.         NSLog(@"Succeeded!");  
  6.         NSLog(@"%@",path);  
  7.     }  
  8.     else  
  9.     {  
  10.         NSLog(@"Failed!");  
  11.     }