0
votes

I'm trying to mirror what is happening in a view on an iPad on an external screen.

func startMirroring() {
    Timer.scheduledTimer(timeInterval:0.05, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
}

func tick() {
    let snapshot = someView.snapshotImage()
    placeSomewhereElse(image: snapshot)
}

extension UIView {
    func snapshotImage() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }
}

The problem

Scrolling in a scrollview will only be reflected in the snapshot after scrolling has ended. I believe the scrollview is not really updating it's view hierarchy and layout during scrolling for efficiency. I need to however capture it during scrolling.

I tried:

  • afterScreenUpdates: true

In scrollViewDidScroll:

  • setNeedsDisplay()
  • layoutIfNeeded()
  • setNeedsLayout()

Is it possible to capture the scrollviews during scrolling?

Edit to clarify:

Hierarchy:

  • UIWindow <- I wanna snapshot this
  • ----UIView
  • --------UIScrollView <- i have no knowledge of this
1

1 Answers

2
votes

Please remove Timer and call startMirroring() method in scrollViewDidScroll, I have tried your scenario and got continuous monitoring of scrollview,

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    print("scrolling")
    startMirroring()
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    print("scrolling ends")
}

func startMirroring() {
    imgView.image = scrollView.snapshotImage()
}

extension UIView {
  func snapshotImage() -> UIImage? {
      UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
      drawHierarchy(in: bounds, afterScreenUpdates: false)
      let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return snapshotImage
  }
}

Hope it will be helpful