2017-08-20 53 views
1

如何在垂直方向上移動水平線? 我可以繪製一條直線,我需要使用長按來移動它。 我該怎麼做?如何移動線?

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

回答

0

可以使用的UIView繪製一條水平線和可以在垂直方向上使用UIView.animate方法通過提供所需的選項移動它。

在你的ViewController定義以下變量:

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

呼叫的drawLine方法內viewDidLoad中方法,並調用你的觸摸事件moveVertically方法:

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

UIView的什麼,如果我有3條線?我如何區分它們並移動所需的? – Vladislav

+0

您可以通過將框架CGRect傳遞給方法來繪製三條線,並調用要移動的線條實例的moveVertically方法。所以你可以按照你的要求修改上面的代碼。 –

+0

上面的代碼是繪製一條線並將其沿垂直方向移動。 –

0

你可以做的是汲取一個UIView這條線,然後向上移動的UIView或到任何位置,你想,像這樣:

UIView.animate(withDuration: 0.3, animations: { 
       yourView.origin = CGPoint(yourView.frame.origin.x, yourYPosition) 

      }, completion: { (value: Bool) in 
       //do anything after animation is done 
      }) 
+0

是否有可能使用UIImageView做到這一點?當然 – Vladislav

+0

是,剛剛更換的UIImageView –