【问题标题】:iOS 7 taking screenshot of part of a UIViewiOS 7 截取部分 UIView
【发布时间】:2013-12-13 02:24:37
【问题描述】:

我有一个 400x320 的视图 (testView),我需要截取该视图的一部分(比如 rect = (50, 50, 200, 200))。 我正在使用 iOS 7 中的 drawViewHierarchy 方法,但我不知道如何正确地做到这一点。

    UIGraphicsBeginImageContextWithOptions(self.testView.bounds.size, NO, [UIScreen mainScreen].scale);

    [self.testView drawViewHierarchyInRect:self.testView.bounds afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

任何帮助将不胜感激!

谢谢。

【问题讨论】:

    标签: ios objective-c uiview ios7


    【解决方案1】:

    获得整个快照后,您可以在较小的图形上下文中绘制它,从而获得所需的部分:

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, [UIScreen mainScreen].scale);
    [image drawInRect:CGRectMake(-50, -50, image.size.width, image.size.height)];
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    编辑:更好的是,直接在较小的上下文中绘制层次结构:

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, [UIScreen mainScreen].scale);
    [self.testView drawViewHierarchyInRect:CGRectMake(-50, -50, self.testView.bounds.size.width, self.testView.bounds.size.height) afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    【讨论】:

    • 谢谢!这对我帮助很大!
    • 在带有self.hostView.superview!.drawHierarchy(in: frame, afterScreenUpdates: true) 的Swift 中,frame 肯定小于superView,我仍然可以获得完整视图的内容。但它被浓缩为我提供给UIGraphicsBeginImageContextWithOptions()CGSize(我当然和我的framesize 一样)。
    • @meaning-matters 这里的诀窍是通过使用完全相同大小的视图来绘制层次结构(以防止缩放),并偏移它以获得您想要的部分。通过使用UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 200), true, 0),您可以使用view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) 获得视图的左上角200x200 部分。您也可以通过这种方式抵消您获得的部分:view.drawHierarchy(in: UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: -100, left: -100, bottom: 0, right: 0)), afterScreenUpdates: true)。希望对您有所帮助!
    【解决方案2】:

    试试下面的代码行,

    UIView *popSnapshot=[inputView snapshotViewAfterScreenUpdates:YES];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多