Search code examples
swiftanimationcalayer

Draw a horizontal line and move it


I make a barcode scanner in swift, and i want to add an animation with a horizontal red line on the barcode zone, and i want this line to move up and down ...

i try several code with calayer ... i can draw, but i don't know how to move it (with a repeat)

can you help me ?

drawLine(onLayer: view.layer, fromPoint: CGPoint(x:100, y:100), toPoint: CGPoint(x:400, y:100))

func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {

        let line = CAShapeLayer()
        let linePath = UIBezierPath()
        linePath.move(to: start)
        linePath.addLine(to: end)
        line.path = linePath.cgPath
        line.fillColor = nil
        line.opacity = 1.0
        line.strokeColor = UIColor.red.cgColor
        layer.addSublayer(line)
    }

Solution

  • You can draw the line with drawing a basic UIView, or any other way just like you did. Then to move it, you can use UIView.animation

    Just a simple code piece for moving the UIView(not sure if you can use this move any other thing);

    UIView.animate(withDuration: 0.2, delay: 0, options: [.autoreverse, .repeat], animations: { 
         self.view.transform = CGAffineTransform(translationX: newX, y: newY)
    }, completion: nil)