Search code examples
iosswiftxcodeswift3core-graphics

How to move line?


How to move horizontal line in a vertical direction? I can draw a straight horizontal line and I need to move it using long press. How can I do that?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
    if let touch = touches.first 
    {
        let currentPoint = touch.location(in: self.view)
        DrawLine(FromPoint: currentPoint, toPoint: currentPoint)
    }
}
func DrawLine(FromPoint: CGPoint, toPoint: CGPoint)
{
    UIGraphicsBeginImageContext(self.view.frame.size)
    imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
    let context = UIGraphicsGetCurrentContext()
    let lineWidth : CGFloat = 5
    context?.move(to: CGPoint(x: FromPoint.x, y: FromPoint.y))
    context?.addLine(to: CGPoint(x: FromPoint.x + 200, y: FromPoint.y))
    context?.setBlendMode(CGBlendMode.normal)
    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(lineWidth)
    context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
    context?.strokePath()
    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

Solution

  • you can draw a horizontal line using UIView and can move it in vertical direction using UIView.animate method by providing the required options.

    In your ViewController define the following variables:

    var scanlineRect = CGRect.zero
    var scanlineStartY: CGFloat = 0
    var scanlineStopY: CGFloat = 0
    var topBottomMargin: CGFloat = 30
    var scanLine: UIView = UIView()
    

    Call drawLine method inside viewDidLoad method and call moveVertically method on your touch event:

    func drawLine() {
            self.addSubview(scanLine)
            scanLine.backgroundColor = UIColor(red: 0.4, green: 0.8, blue: 0.4, alpha: 1.0) // green color
            scanlineRect = CGRect(x: 0, y: 0, width: self.frame.width, height: 2)
            scanlineStartY = topBottomMargin
            scanlineStopY = self.frame.size.height - topBottomMargin
        }
    
    func moveVertically() {
            scanLine.frame  = scanlineRect
            scanLine.center = CGPoint(x: scanLine.center.x, y: scanlineStartY)
            scanLine.isHidden = false
            weak var weakSelf = scanLine
            UIView.animate(withDuration: 1.0, delay: 0.0, options: [.repeat, .autoreverse, .beginFromCurrentState], animations: {() -> Void in
                weakSelf!.center = CGPoint(x: weakSelf!.center.x, y: scanlineStopY)
                }, completion: nil)
        }