*更新發佈後不久,我發現這看起來有我所有的答案。還沒有爲自己工作,但這可能會幫助其他人有類似的問題。 Scratch Card effect in Swift 3末更新*swift 3使用圖層通過繪製「清晰」線條來顯示圖像
這是我第一次到棧中,以便道歉,如果這是一個有點「小白」問題。我的問題有兩個部分。我已經使用了幾個教程,告訴我如何在imageView中的圖像上繪製線條,但是我正努力實現通過在圖層上繪製「清晰」線條來顯示覆蓋層下面的圖像的目標。想象一張刮刮卡......這就是我所追求的效果。
我已經使用了以下Stack問題/答案來幫助指導我最初Draw a line realtime with Swift 3.0;但是我的最終目標受到圖像/視圖邊界混淆的進一步阻礙。
上面的教程非常適合初始繪圖,除了當我觸摸屏幕時,我的手指位置被轉換爲imageView座標,所以線條永遠不會出現在我放置手指的位置。我真的很喜歡有人幫助我轉換座標,這樣我的手指就能確切畫出線條。我試着改變'Draw line'func的邊界,但是我從圖像中得到了奇怪的行爲,並且繪圖完全停止工作。
如果有人能夠幫助解決這兩個問題,我會非常感激。如果我需要分解問題,那麼我會這樣做。如果有幫助,我附上我的代碼。感謝您看...
class ViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
var layer: CALayer {
return myImageView.layer
}
var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: self.view)
}
}
func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
myImageView.image?.draw(in: view.bounds)
let context = UIGraphicsGetCurrentContext()
context?.move(to: fromPoint)
context?.addLine(to: toPoint)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()
myImageView.image = UIGraphicsGetImageFromCurrentImageContext()
myImageView.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: view)
drawLine(from: lastPoint, to: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !swiped {
// draw a single point
self.drawLine(from: lastPoint, to: lastPoint)
}
}
func setUpLayer() {
layer.backgroundColor = UIColor.clear.cgColor
layer.borderWidth = 10.0
layer.borderColor = UIColor.red.cgColor
layer.shadowOpacity = 0.7
layer.shadowRadius = 10.0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myImageView.image = UIImage(named: "8BitGirls.png")
setUpLayer()
}
}
嗨@Josh,感謝您的幫助。這有助於我理解爲什麼coords已經出來,但是我試着將你的代碼放到我的drawline函數中,並且它沒有工作......你能建議它需要轉換的地方嗎? –