画一条水平线并移动它

Draw a horizontal line and move it

我在swift中制作了一个条码扫描仪,我想在条码区域添加一个带有水平红线的动画,我希望这条线上下移动...

我用 calayer 尝试了几个代码...我可以画画,但我不知道如何移动它(重复)

你能帮帮我吗?

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)
    }

您可以使用基本画法 UIView 来画线,也可以像您一样使用任何其他方式画线。然后移动它,你可以使用UIView.animation

只是一个简单的代码片段,用于移动 UIView(不确定您是否可以使用此移动任何其他东西);

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