我试图制作带有用户可以绘制内容的视图的屏幕。我用这样的代码创建了自定义视图:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: imageView)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: imageView)
drawLine(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !swiped {
// draw a single point
drawLine(fromPoint: lastPoint, toPoint: lastPoint)
}
和绘图功能
func drawLine(fromPoint: CGPoint, toPoint: CGPoint) {
UIGraphicsBeginImageContext(imageView.frame.size)
let context = UIGraphicsGetCurrentContext()
imageView.image?.draw(in: CGRect(x: 0, y: 0, width: imageView.frame.size.width, height: imageView.frame.size.height))
context?.move(to: fromPoint)
context?.addLine(to: toPoint)
context?.setLineCap(.round)
context?.setLineWidth(lineWidth)
context?.setStrokeColor(lineColor.cgColor)
context?.strokePath()
imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
当我在视图控制器中显示该视图时,一切正常:
但是当我在UISplitViewController中的详细视图中显示它时,当用户继续绘图时,部分已经绘制了图像移动和淡出:
我无法找到关于网络中的哪些错误的内容,也不知道是什么产生了这样的行为
有人对此有任何想法吗?
这是您可以重现该错误的示例项目: https://github.com/fizzy871/DrawingBug
不过,在实际项目中,不仅分割视图控制器的主视图,而且导航栏也影响绘图答案 0 :(得分:1)
原来它的行为是这样的,因为imageView框架的大小是小数部分。
我只是将绘图上下文乘以2并解决了问题:
func drawLine(fromPoint fromPoint: CGPoint, toPoint: CGPoint) {
// multiply to avoid problems when imageView frame value is XX.5
let fixedFrameForDrawing = CGRect(x: 0, y: 0, width: imageView.frame.size.width*2, height: imageView.frame.size.height*2)
let point1 = CGPoint(x: fromPoint.x*2, y: fromPoint.y*2)
let point2 = CGPoint(x: toPoint.x*2, y: toPoint.y*2)
UIGraphicsBeginImageContext(fixedFrameForDrawing.size)
if let context = UIGraphicsGetCurrentContext() {
imageView.image?.draw(in: fixedFrameForDrawing)
context.move(to: point1)
context.addLine(to: point2)
context.setLineCap(.round)
context.setLineWidth(lineWidth*2)
context.setStrokeColor(lineColor.cgColor)
context.strokePath()
let imageFromContext = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = imageFromContext
}