iOS 屏幕截图和保存到相册以及图片的缩放

如果iOS 想截取游戏的屏幕,能不能截取?反正如下的代码是不能截取的,只能截取一个空白的内容。原因可能是,我说的可能哈,没有自己验证,可能拿到的上下文不是拿到游戏的上下文。如何截取屏幕,请使用 Unity 截取屏幕并通过 iOS SDK 保存在 iOS 手机上。具体实现请参考[Unity iOS保存截图到iOS相册]。

//截屏 此处截取游戏画面失败
-(void)shortCut{

    UIWindow*screenWindow = [[UIApplication sharedApplication] keyWindow];
    
    #ifdef DEBUG
    NSLog(@"游戏的窗口的数据:%@",screenWindow);
    #endif
    UIGraphicsBeginImageContext(screenWindow.frame.size);
    
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    self.shotCutImage =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    }
#pragma mark- 缩放图片比例
+ (UIImage*)imageCompressWithSimple:(UIImage*)image scale:(float)scale
{
    CGSize size = image.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGFloat scaledWidth = width * scale;
    CGFloat scaledHeight = height * scale;
    UIGraphicsBeginImageContext(size); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
#pragma mark- 缩放图片尺寸
if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
        return self;
    }

    CGSize scaledSize = size;
    CGPoint thumbnailPoint = CGPointZero;

    CGFloat widthFactor = size.width / self.size.width;
    CGFloat heightFactor = size.height / self.size.height;
    CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
    scaledSize.width = self.size.width * scaleFactor;
    scaledSize.height = self.size.height * scaleFactor;

    //计算图片的位置
    if (widthFactor > heightFactor) {
        thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
    }
    else if (widthFactor < heightFactor) {
        thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
    }

        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

        [self drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return newImage;
    }



//保存图片到相册
- (void)saveButtonEventWithImage:(UIImage *)image
{
    //保存完后调用的方法
    SEL selector = @selector(onCompleteCapture:didFinishSavingWithError:contextInfo:);
    //保存
    UIImageWriteToSavedPhotosAlbum(image, self, selector, NULL);
}

//图片保存完后调用的方法
- (void)onCompleteCapture:(UIImage *)screenImage didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error){
        //保存失败
#ifdef DEBUG
        NSLog(@"屏幕截图保存相册失败:%@",error);
#endif
    }else {
        //保存成功
#ifdef DEBUG
        NSLog(@"屏幕截图保存相册成功");
#endif
    }
}

你可能感兴趣的:(iOS 屏幕截图和保存到相册以及图片的缩放)