I have been working on being able to draw a red line on an image view using swift 3.0 and have ran across some problems. As you could guess, I am using some code from stack overflow to help me with my first initial attempt at this and am getting a weird bug.
As I drag my finger across the imageview it does draw a red line but for each "frame" it drops all that I drew down further on the screen. So as I draw it looks like the lines I am drawing are falling and then just completely go off screen.
What I am looking for is to be able to simply draw on the image view and instead of everything moving down each frame, I would like it to keep in the same position similar to how it works on all the drawing apps and etc.
Below is all the code:
@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var fromPoint = CGPoint();
var toPoint = CGPoint.zero
var red: CGFloat = 255.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 viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
{
UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, false, 0);
mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
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()
mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
mainImageView.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = false;
if let touch = touches.first {
lastPoint = touch.location(in: self.mainImageView)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true;
if let touch = touches.first {
let currentPoint = touch.location(in: mainImageView)
drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if(!swiped){
self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
}
}
Thanks for the help guys!
Following code you can Draw the image using touch (Swift 3.0)
Following code you can Draw the image using touch