受tutsline的启发,我实现了自己的Swift 4放大镜视图类以适应我们的需求,除了两个用例之外,该类都运行良好。
我们正在使用放大镜来放大UIImageView的内容。
UIImageView
的某个区域开始触摸时,放大镜会显示黑色内容。 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!)
}
}
有人可以向我解释一下,如何避免在上下文中呈现“无内容”吗?有没有办法检查是否存在可渲染的内容?
这是当触摸位置位于可以呈现的内容上时的外观图像:
编辑:因为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()
}
}
答案 0 :(得分:0)
我今天遇到了同样的问题,我注意到它重复了以前的内容,解决方案是在layer.render之前清除上下文
context.clear(rect)