Objective-C:在自定义框架内捕获所有视图的屏幕截图

4
我有一个游戏,用户可以创建自定义关卡并将它们上传到我的服务器供其他用户玩,并且我想在用户测试他/她的关卡之前获取“动作区域”的屏幕截图,作为一种“预览图像”。
我知道如何获取整个视图的屏幕截图,但我想将其定义为自定义框架。请参考以下图片:
我想只拍摄红色区域,“动作区域”的屏幕截图。我能做到吗?
2个回答

14

你只需要创建一个矩形来指定要捕获的区域,并将该矩形传递给方法即可。

Swift 3.x:

extension UIView {
  func imageSnapshot() -> UIImage {
    return self.imageSnapshotCroppedToFrame(frame: nil)
  }

  func imageSnapshotCroppedToFrame(frame: CGRect?) -> UIImage {
    let scaleFactor = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, scaleFactor)
    self.drawHierarchy(in: bounds, afterScreenUpdates: true)
    var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    if let frame = frame {
        let scaledRect = frame.applying(CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))

        if let imageRef = image.cgImage!.cropping(to: scaledRect) {
            image = UIImage(cgImage: imageRef)
        }
    }
    return image
  }
}

//How to call :
imgview.image = self.view.imageSnapshotCroppedToFrame(frame: CGRect.init(x: 0, y: 0, width: 320, height: 100))

Objective C:

-(UIImage *)captureScreenInRect:(CGRect)captureFrame 
{
    CALayer *layer;
    layer = self.view.layer;
    UIGraphicsBeginImageContext(self.view.bounds.size); 
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;
}

//How to call :
imgView.image = [self captureScreenInRect:CGRectMake(0, 0, 320, 100)];

1
- (UIImage *) getScreenShot {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接