I have the following code (within an extension of UIView
) that fragments a UIView
into a certain number of pieces:
public func fragment(into numberOfFragments: Int) -> [UIView] {
var fragments = [UIView]()
guard let containerView = superview, let snapshot = snapshotView(afterScreenUpdates: true) else { return fragments }
let fragmentWidth = snapshot.frame.width / CGFloat(numberOfFragments)
let fragmentHeight = snapshot.frame.height / CGFloat(numberOfFragments)
for x in stride(from: 0.0, to: snapshot.frame.width, by: fragmentWidth) {
for y in stride(from: 0.0, to: snapshot.frame.height, by: fragmentHeight) {
let rect = CGRect(x: x, y: y, width: fragmentWidth, height: fragmentHeight)
if let fragment = snapshot.resizableSnapshotView(from: rect, afterScreenUpdates: true, withCapInsets: .zero) {
fragment.frame = convert(rect, to: containerView)
containerView.addSubview(fragment)
fragments.append(fragment)
}
}
}
return fragments
}
However, for numberOfFragments=20
this code takes about 2 seconds to complete. Is there any way of achieving this same result in a faster way? Should I be using an animation/transition instead?
Thanks a lot.
This solution uses UIImageViews instead of UIViews. It crops a single captured screenshot instead of calling the much more expensive
resizableSnapshotView
400 times. Time went from ~2.0 seconds down to 0.088 seconds ifafterScreenUpdates
is set to false (which works for my test case). IfafterScreenUpdates
is required for your purposes, then the time is about 0.15 seconds. Still - much much faster than 2.0 seconds!