[ad_1]
I have a logic for erasing a picture by pan gesture
@IBAction private func didPan(_ sender: UIPanGestureRecognizer) {
let location = sender.location(in: scrollView)
switch viewModel?.currentOption.value {
case .manualErase:
handleManualEresGesture(location: convertTapToImg(location) ?? .zero, eraseViewLocation: sender.location(in: editingImageView))
default:
break
}
}
private func manualErase(rect: CGRect) {
UIGraphicsBeginImageContextWithOptions(editingImageView.frame.size, false, 0)
editingImageView.image?.draw(in: CGRect(origin: .zero, size: editingImageView.frame.size))
UIGraphicsGetCurrentContext()?.setLineCap(.round)
UIGraphicsGetCurrentContext()?.setLineWidth(rect.size.width)
UIGraphicsGetCurrentContext()?.setBlendMode(.clear)
UIGraphicsGetCurrentContext()?.setStrokeColor(UIColor.clear.cgColor)
UIGraphicsGetCurrentContext()?.beginPath()
UIGraphicsGetCurrentContext()?.setShouldAntialias(true)
UIGraphicsGetCurrentContext()?.move(to: rect.origin)
UIGraphicsGetCurrentContext()?.addLine(to: rect.origin)
UIGraphicsGetCurrentContext()?.strokePath()
editingImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func handleManualEresGesture(location: CGPoint, eraseViewLocation: CGPoint = .zero) {
manualFrameEraseView.center = eraseViewLocation
let size = CGSize(width: CGFloat(eraseSizeSlider.value), height: CGFloat(eraseSizeSlider.value))
manualErase(rect: CGRect(origin: location, size: size))
}
func convertTapToImg(_ point: CGPoint) -> CGPoint? {
let xRatio = editingImageView.frame.width / editingImageView.image!.size.width
let yRatio = editingImageView.frame.height / editingImageView.image!.size.height
let ratio = min(xRatio, yRatio)
let imgWidth = editingImageView.image!.size.width * ratio
let imgHeight = editingImageView.image!.size.height * ratio
var tap = point
var borderWidth: CGFloat = 0
var borderHeight: CGFloat = 0
// detect border
if ratio == yRatio {
// border is left and right
borderWidth = (editingImageView.frame.size.width - imgWidth) / 2
if point.x < borderWidth || point.x > borderWidth + imgWidth {
return nil
}
tap.x -= borderWidth
} else {
// border is top and bottom
borderHeight = (editingImageView.frame.size.height - imgHeight) / 2
if point.y < borderHeight || point.y > borderHeight + imgHeight {
return nil
}
tap.y -= borderHeight
}
let xScale = tap.x / (editingImageView.frame.width - 2 * borderWidth)
let yScale = tap.y / (editingImageView.frame.height - 2 * borderHeight)
let pixelX = editingImageView.image!.size.width * xScale
let pixelY = editingImageView.image!.size.height * yScale
return CGPoint(x: pixelX, y: pixelY)
}
and without using scroll view, this code works well!
but using scrollView it shrinks and behaves unpredictably (video at link)
https://drive.google.com/file/d/1zp9cBPMJq3LfsI0RsjjDX6Nnv317Rsgd/view?usp=sharing
while zooming, the picture shrinks and becomes larger
please help me with it
[ad_2]
Source link