ios - 怎么移线?

标签 ios swift xcode swift3 core-graphics

如何在垂直方向上移动水平线? 我可以画一条水平直线,我需要使用长按来移动它。 我该怎么做?

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

最佳答案

您可以使用 UIView 绘制水平线,并可以通过提供所需选项使用 UIView.animate 方法在垂直方向移动它。

在您的 ViewController 中定义以下变量:

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

viewDidLoad 方法中调用 drawLine 方法,并在触摸事件中调用 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)
    }

关于ios - 怎么移线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780797/

相关文章:

ios - 将数字格式化为百分比

ios - Swift Object Mapper 传递不同的日期

swift - 将图像添加到 ActionSheet 并将其放在右侧

ios - 从 unity 3 升级后,Xcode 无法解析从 Unity 4 导出的项目

ios - 为参数 "invalid value"提供了一个 'appIdName'?

iphone - iOS - 将 iPhone 版本转换为 iPad

objective-c - PDF 解析为 NSString

ios - 无法使用类型为 'Double' 的参数列表调用类型为 '(String?)' 的初始值设定项

ios - 如何使用图像和标签制作自定义正确的 UIBarButtonItem?

ios - Xcode 6.4 错误?源代码文本消失。 OSX优胜美地