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. }  

  

同时可以保存

保存文件

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:

-(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

UIView *view = [[[[[UIApplication sharedApplication] windows] objectAtIndex:1] subviews] lastObject];//获得某个window的某个subView
 
    NSInteger index = 0;//用来给保存的png命名
    for (UIView *subView in [view subviews]) {//遍历这个view的subViews
        if ([subView isKindOfClass:NSClassFromString(@"UIImageView")] || [subView isKindOfClass:NSClassFromString(@"UIThreePartButton")]) {//找到自己需要的subView
            //支持retina高分的关键
            if(UIGraphicsBeginImageContextWithOptions != NULL)
            {
                UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0);
            } else {
                UIGraphicsBeginImageContext(subView.frame.size);
            }            
 
            //获取图像
            [subView.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
 
            //保存图像
            NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/%d.png",index];
            if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) {
                index += 1;
                NSLog(@"Succeeded!");
            }
            else {
                NSLog(@"Failed!");
            }
        }
    }



你可能感兴趣的:(游戏,layer,相册)