Vladislav
Vladislav

Reputation: 273

How to draw lines using UIView?

I can draw lines using CGContext. How to draw lines with the same coordinates using UIView? I want to move lines in the future, so that I need to use UIView.

func DrawLine()
{
    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: 100, y: 100))
    context?.addLine(to: CGPoint(x: self.view.frame.width - 100, y: 100))
    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()

    context?.move(to: CGPoint(x: self.view.frame.width/2, y: 100))
    context?.addLine(to: CGPoint(x: self.view.frame.width/2, y: 700))
    context?.strokePath()

    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}
override func viewDidLoad() 
{        
    super.viewDidLoad()
    DrawLine()
}

Upvotes: 1

Views: 942

Answers (1)

Lou Franco
Lou Franco

Reputation: 89142

  1. Add a CAShapeLayer to a UIView

    let shapeLayer = CAShapeLayer()
    view.layer.addSublayer(shapeLayer)
    
  2. set the shapelayer path to the lines

    shapeLayer.path = // some CGPath you create
    

See: https://stackoverflow.com/a/40556796/3937 for how to make a CGPath with lines.

Upvotes: 2

Related Questions