我正在尝试开发一个应用程序,允许用户通过拖动手指(例如Snapchat)来拍照并在照片上绘画。我非常接近要使该功能正常工作,但是我遇到了一个问题,我认为这与UIImageView的contentMode某种程度上有关,这弄乱了我的行的位置。在屏幕边缘最明显。如果我使用scaleAspectFill并尝试用手指跟踪屏幕的边缘,则会看到以下内容:
如您所见,左侧和底部的线不在屏幕上。如果我使用scaleAspectFit并执行相同的操作,则结果如下:
在这种情况下,左侧和底部正确,而右侧/顶部不正确。我的绘图代码如下:
var lastPoint:CGPoint!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if self.capturedImageView.isHidden == false && self.isDrawing {
self.lastPoint = CGPoint(x: touches.first!.location(in: self.capturedImageView).x, y: touches.first!.location(in: self.capturedImageView).y)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if (self.capturedImageView.isHidden == false && lastPoint != nil && self.isDrawing) {
self.capturedImageView.image = self.drawLine(onImage: self.capturedImageView.image!, fromPoint: CGPoint(x: touches.first!.location(in: self.capturedImageView).x, y: touches.first!.location(in: self.capturedImageView).y), toPoint: lastPoint)
}
self.lastPoint = CGPoint(x: touches.first!.location(in: self.capturedImageView).x, y: touches.first!.location(in: self.capturedImageView).y)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.lastPoint = nil
}
//drawLine creates a new UIImage with the desired line drawn on it,
//which I then use to replace capturedImageView.image
func drawLine(onImage: UIImage, fromPoint: CGPoint, toPoint: CGPoint) -> UIImage {
// Create a context of the starting image size and set it as the current one
UIGraphicsBeginImageContext(onImage.size)
// Draw the starting image in the current context as background
onImage.draw(at: CGPoint.zero)
// Get the current context
let context = UIGraphicsGetCurrentContext()!
// Draw a red line
context.setLineWidth(5.0)
context.setStrokeColor(UIColor.red.cgColor)
context.move(to: fromPoint)
context.addLine(to: toPoint)
context.strokePath()
// Save the context as a new UIImage
let myImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Return modified image
return myImage!
}
我认为我做错了,因为UIImageView本身的触摸坐标与UIImageView图像内的坐标不同。不过,我真的很困惑如何解决此问题。如何获取触摸的位置而不是CapturedImageView中的touchedImageView.image中?