[英]draw a straight line in swift 3 and core graphics
我正在嘗試使用核心圖形和swift 3繪制單個直線。然而,當調用touchesmoved時,它會創建多條線而不是一條線。 使用的代碼如下:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var drawingPlace: UIImageView!
var startTouch : CGPoint?
var secondTouch : CGPoint?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
startTouch = touch?.location(in: drawingPlace)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
secondTouch = touch.location(in: drawingPlace)
UIGraphicsBeginImageContext(drawingPlace.frame.size)
drawingPlace.image?.draw(in: CGRect(x: 0, y: 0, width: drawingPlace.frame.width, height: drawingPlace.frame.height))
let bezier = UIBezierPath()
bezier.move(to: startTouch!)
bezier.addLine(to: secondTouch!)
bezier.close()
bezier.lineWidth = 4
UIColor.blue.set()
bezier.stroke()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
drawingPlace.image = img
}
}
}
btw touchesEnd創建一條線,但僅在用戶結束觸摸后。 我希望用戶在觸摸時看到正在繪制的線條。 謝謝。
您需要保持當前context
直到線條繪制過程結束,之后您需要保留當前圖像並清除context
,再次繪制保存的圖像,並繪制新線條。 當觸摸結束時調用清理當前context
並保存當前圖像,之后再次開始新的線條繪制過程
這是完整的代碼
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var drawingPlace: UIImageView!
var startTouch : CGPoint?
var secondTouch : CGPoint?
var currentContext : CGContext?
var prevImage : UIImage?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
startTouch = touch?.location(in: drawingPlace)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
secondTouch = touch.location(in: drawingPlace)
if(self.currentContext == nil)
{
UIGraphicsBeginImageContext(drawingPlace.frame.size)
self.currentContext = UIGraphicsGetCurrentContext()
}else{
self.currentContext?.clear(CGRect(x: 0, y: 0, width: drawingPlace.frame.width, height: drawingPlace.frame.height))
}
self.prevImage?.draw(in: self.drawingPlace.bounds)
let bezier = UIBezierPath()
bezier.move(to: startTouch!)
bezier.addLine(to: secondTouch!)
bezier.close()
UIColor.blue.set()
self.currentContext?.setLineWidth(4)
self.currentContext?.addPath(bezier.cgPath)
self.currentContext?.strokePath()
let img2 = self.currentContext?.makeImage()
drawingPlace.image = UIImage.init(cgImage: img2!)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.currentContext = nil
self.prevImage = self.drawingPlace.image
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.