Objective-C:截取自定义框架内所有视图的截图

我有一个游戏,用户可以创build自定义关卡并将其上传到我的服务器以供其他用户玩,我希望在用户testing自己的关卡之前获得“行动区域”的截图,以便上传到我的服务器一个“预览图像”。

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

行动区

我只想把这个区域的截图做成“行动区”。 我能做到吗?

只要你需要做一个你想要捕捉的区域,并通过方法中的矩形。

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

目标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)]; 
 - (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; }