开发者

iPhone, reproduce the magnifier effect

I would like be able to c开发者_开发技巧reate 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 how to start, do you have any idea?

Thanks in advance for your help :)


We do this in Crosswords. In your drawRect method, mask off a circle (using a monochrome bitmap containing the 'mask' of your magnifying glass) and draw your subject view in there with a 2x scale transform. Then draw a magnifying glass image over that and you're done.

- (void) drawRect: (CGRect) rect {
    CGContextRef    context = UIGraphicsGetCurrentContext();
    CGRect          bounds = self.bounds;
    CGImageRef      mask = [UIImage imageNamed: @"loupeMask"].CGImage;
    UIImage         *glass = [UIImage imageNamed: @"loupeImage"];

    CGContextSaveGState(context);
    CGContextClipToMask(context, bounds, mask);
    CGContextFillRect(context, bounds);
    CGContextScaleCTM(context, 2.0, 2.0);

    //draw your subject view here

    CGContextRestoreGState(context);

    [glass drawInRect: bounds];
}


There is a complete example over here. There is a minor error in the downloaded project but otherwise it works great and does exactly what you need.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜