2017-02-19 98 views
0

我试图让屏幕上的视图在哪个用户可以绘制的东西。我创建了这样的代码的自定义视图:在UISplitViewController中绘制的奇怪错误

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() 
} 

当我表明,鉴于视图控制器一切正常:

enter image description here

但是当我显示它在UISplitViewController中详细查看,而用户继续绘制时,部分已经画出了图像的移动和淡出: enter image description here

我找不到什么漏洞在网络,而且不知道什么是产生这种行为

是否有人想过这事任何想法什么?

也就是说例子项目,您可以重现错误: https://github.com/fizzy871/DrawingBug

顺便说一句,在实际工程没有拆分视图控制器的唯一主视图,但导航栏会影响绘制过

回答

1

原来,它的行为这种方式是因为imageView框架具有小数部分的大小。

enter image description here

我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 
    } 
+0

这只是发生在我的应用程序,疯狂的事情。现在我调整了框架大小,它工作正常。它一定很难弄清楚,谢谢你的解决方案! –