iPhone, reproduce the magnifier effect

前端 未结 3 1586
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 11:45

I would like be able to create a movable magnifier (like the one you have when you copy and paste) in a custom view, for zooming a part of my view.

I have no idea on

3条回答
  •  感情败类
    2020-12-04 12:14

    I use this code in Swift 3 :

    class MagnifyingGlassView: UIView {
    
        var zoom: CGFloat = 2 {
            didSet {
                setNeedsDisplay()
            }
        }
    
        weak var readView: UIView?
    
        // MARK: - UIVIew
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupView()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupView()
        }
    
        override func draw(_ rect: CGRect) {
            guard let readView = readView else { return }
            let magnifiedBounds = magnifyBounds(of: readView, zoom: zoom)
            readView.drawHierarchy(in: magnifiedBounds, afterScreenUpdates: false)
        }
    
        // MARK: - Private
    
        private func setupView() {
            isOpaque = false
            backgroundColor = UIColor.clear
        }
    
        private func magnifyBounds(of view: UIView, zoom: CGFloat) -> CGRect {
            let transform = CGAffineTransform(scaleX: zoom, y: zoom)
            var bounds = view.bounds.applying(transform)
            bounds.center = view.bounds.center
            return view.convert(bounds, to: self)
        }
    }
    
    extension CGRect {
        var center: CGPoint {
            get {
                return CGPoint(x: origin.x + width / 2, y: origin.y + height / 2)
            }
            set {
                origin.x = newValue.x - width / 2
                origin.y = newValue.y - height / 2
            }
        }
    }
    

    You need to call setNeedsDisplay in scrollViewDidScroll: if your read view is a scrollView.

提交回复
热议问题