2017-02-19 100 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

這只是發生在我的應用程序,瘋狂的事情。現在我調整了框架大小,它工作正常。它一定很難弄清楚,謝謝你的解決方案! –