iOS实现截屏 并合适保存

开发游戏时,往往会有这么一个需求:在某个成就达成或者破纪录时,需要截个屏,然后发送到微博上与好友/粉丝分享,虽然home + 开机键组合可手动截屏,在Cocos2d有个CCRenderTexture类,借助该类可很容易实现代码截取功能。使用CCRenderTexture,我们可以截取游戏场景、某个Layer,甚至是精灵:

  1. /**游戏截图  
  2.  *@param node 需要截取的控件  
  3. */  
  4. - (void)snapshotScreen:(CCNode*)node   
  5. {   
  6.     //取得屏幕大小   
  7.     CGSize winSize = [[CCDirector sharedDirector]winSize];   
  8.     CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width   
  9.                                                                       height:winSize.height];   
  10.     [renderTexture begin];   
  11.     [node visit];   
  12.     [renderTexture end];   
  13.     [renderTexture cleanup];   
  14.     UIImage *snapshot = [renderTexture getUIImageFromBuffer];   
  15.     //把截图保存到相册里   
  16.     UIImageWriteToSavedPhotosAlbum(snapshot, nil, nil, nil);   
  17. }  

  

如果游戏支持高清模式,上面代码截出来的图是960 * 640大小的,这个尺寸如果要上传到微博上,文件的大小可能会超出限制,那么在上传前可用先把截图大小缩小点如480*320,以减少图片体积:

  1. /** 调整图片大小*/  
  2. - (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size   
  3. {   
  4.     UIGraphicsBeginImageContext(size);   
  5.     [image drawInRect:CGRectMake(0, 0, size.width, size.height)];   
  6.     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();   
  7.     UIGraphicsEndImageContext();   
  8.     return newImage;   
  9. }  

  

同时可以保存

  1. 保存文件  
  2.   
  3. UIImage *m_imgFore=......;  
  4.   
  5. //png格式   
  6.   
  7. NSData *imagedata=UIImagePNGRepresentation(m_imgFore);  
  8.   
  9. //JEPG格式   
  10.   
  11. //NSData *imagedata=UIImageJEPGRepresentation(m_imgFore,1.0);   
  12.   
  13. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);  
  14.   
  15. NSString *documentsDirectory=[paths objectAtIndex:0];   
  16.   
  17. NSString *savedImagePath=[documentsDirectorystringByAppendingPathComponent:@"saveFore.png"];  
  18.   
  19. [imagedata writeToFile:savedImagePath atomically:YES];  
  20.   
  21. 或者  
  22.   
  23. [fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.png"] contents:data attributes:nil];    将图片保存为PNG格式  
  24.   
  25.  [fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];   将图片保存为JPEG格式  
保存文件

UIImage *m_imgFore=......;

//png格式

NSData *imagedata=UIImagePNGRepresentation(m_imgFore);

//JEPG格式

//NSData *imagedata=UIImageJEPGRepresentation(m_imgFore,1.0);

NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *documentsDirectory=[paths objectAtIndex:0]; 

NSString *savedImagePath=[documentsDirectorystringByAppendingPathComponent:@"saveFore.png"];

[imagedata writeToFile:savedImagePath atomically:YES];

或者

[fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.png"] contents:data attributes:nil];    将图片保存为PNG格式

 [fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];   将图片保存为JPEG格式


如果不是cocos2D开发,则使用如下代码:

方法1:

  1. -(void)screenShots  
  2. {  
  3.     CGSize imageSize = [[UIScreen mainScreen] bounds].size;  
  4.     if (NULL != UIGraphicsBeginImageContextWithOptions) {  
  5.         UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);  
  6.     }  
  7.     else  
  8.     {  
  9.         UIGraphicsBeginImageContext(imageSize);  
  10.     }  
  11.       
  12.     CGContextRef context = UIGraphicsGetCurrentContext();  
  13.       
  14.     for (UIWindow * window in [[UIApplication sharedApplication] windows]) {  
  15.         if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {  
  16.             CGContextSaveGState(context);  
  17.             CGContextTranslateCTM(context, [window center].x, [window center].y);  
  18.             CGContextConcatCTM(context, [window transform]);  
  19.             CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);  
  20.             [[window layer] renderInContext:context];  
  21.               
  22.             CGContextRestoreGState(context);  
  23.         }  
  24.     }  
  25.       
  26.     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
  27.       
  28.     UIGraphicsEndImageContext();  
  29.     UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);  
  30.     NSLog(@"Suceeded!");  
  31. }  
-(void)screenShots
{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    if (NULL != UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    }
    else
    {
        UIGraphicsBeginImageContext(imageSize);
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            CGContextConcatCTM(context, [window transform]);
            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);
            [[window layer] renderInContext:context];
            
            CGContextRestoreGState(context);
        }
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    NSLog(@"Suceeded!");
}

(注意:方法1截图后会是竖屏,所以需要配合UIImage旋转的方法判断方向后旋转才能合适保存,见文章旋转翻转UIImage 不是UIImageView 适用于源图像的处理,例如截图后旋转)


所以再提供另外一方法:

方法2

  1. UIView *view = [[[[[UIApplication sharedApplication] windows] objectAtIndex:1] subviews] lastObject];//获得某个window的某个subView   
  2.    
  3.     NSInteger index = 0;//用来给保存的png命名   
  4.     for (UIView *subView in [view subviews]) {//遍历这个view的subViews   
  5.         if ([subView isKindOfClass:NSClassFromString(@"UIImageView")] || [subView isKindOfClass:NSClassFromString(@"UIThreePartButton")]) {//找到自己需要的subView   
  6.             //支持retina高分的关键   
  7.             if(UIGraphicsBeginImageContextWithOptions != NULL)  
  8.             {  
  9.                 UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0);  
  10.             } else {  
  11.                 UIGraphicsBeginImageContext(subView.frame.size);  
  12.             }              
  13.    
  14.             //获取图像   
  15.             [subView.layer renderInContext:UIGraphicsGetCurrentContext()];  
  16.             UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
  17.             UIGraphicsEndImageContext();  
  18.    
  19.             //保存图像   
  20.             NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/%d.png",index];  
  21.             if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) {  
  22.                 index += 1;  
  23.                 NSLog(@"Succeeded!");  
  24.             }  
  25.             else {  
  26.                 NSLog(@"Failed!");  
  27.             }  
  28.         }  
  29.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值