Sunday, 2 September 2018

Speeding up the fragmentation of a view

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.



from Speeding up the fragmentation of a view

No comments:

Post a Comment