仅当有要渲染的东西时才执行layer.render(在上下文中:)

问题描述 投票:1回答:1

tutsline的启发,我已经实现了自己的Swift 4放大镜视图类以适应我们的需求,除了两个用例之外,它都运行良好。

我们正在使用放大镜来放大UIImageView的内容。

  1. 当触摸开始于UIImageView的区域,其中没有图像时,放大镜显示黑色内容

enter image description here

  1. 当触摸离开图像所在的区域时,放大镜会重复显示最后可见的内容

enter image description here

draw(_ rect:)方法的代码如下:

    // Called by the didSet of touchPoint and the ios view lifecylce
    override public func draw(_ rect: CGRect) {

        super.draw(rect)

        guard let magnifyingView = viewToMagnify else { fatalError("class WWMagnifierView seems to be used without having set a view to magnify.") }

        if touchPoint != CGPoint.zero {

            let context = UIGraphicsGetCurrentContext()

            context!.translateBy(x: 1 * (self.frame.size.width * 0.5), y: 1 * (self.frame.size.height * 0.5))
            context!.scaleBy(x: 1.5, y: 1.5) // 1.5 is the zoom scale
            context!.translateBy(x: -1 * (touchPoint.x), y: -1 * (touchPoint.y))

            magnifyingView.layer.render(in: context!)
        }
    }

有人可以向我解释,如何避免在上下文中呈现“无内容”?有没有办法检查是否存在可渲染的内容?

这是当触摸位置位于可以呈现的内容上时的外观图像:

enter image description here

EDIT:因为Tobi想知道我如何使用MagnifierView ...

// Setup getting called in viewDidAppear to ensure the magnifier works also, when the view appears again on stack.
func setupMagnifier() {

    guard let imageView = imageView else { return }

    if magnifier == nil {

        magnifier = WWMagnifierView(frame: CGRect(x: 30, y: 130, width: 120, height: 120))

        self.view.addSubview(magnifier!)
    }

    magnifier?.viewToMagnify = imageView
}

// Gets triggered from the touch events
func updateMagnifier(for touchLocation: CGPoint) {

    // Update the magnifiers content based on the touch location
    magnifier?.touchPoint = touchLocation
}

此处设置touchPoint会触发didSet关闭,然后...

public var touchPoint = CGPoint.zero {

    didSet {

        self.setNeedsDisplay()
    }
}
ios swift calayer uigraphicscontext
1个回答
0
投票
context.clear(rect)
© www.soinside.com 2019 - 2024. All rights reserved.