4

我有一个游戏,用户可以创建自定义关卡并将它们上传到我的服务器供其他用户玩,我想在用户测试他/她的关卡之前获取“动作区域”的屏幕截图以上传到我的服务器作为排序“预览图像”。

我知道如何获取整个视图的屏幕截图,但我想将其定义为自定义框架。考虑下图:

行动区

我只想截取红色区域的屏幕截图,即“行动区域”。我能做到这一点吗?

4

2 回答 2

14

只需要制作要捕获的区域的矩形并在方法中传递矩形。

斯威夫特 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))

目标 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)];
于 2013-09-08T02:51:54.320 回答
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;
}
于 2015-08-06T12:11:55.977 回答