6

I am new to swift, I want to draw a line between 2 points over an image which I called mapView, I tried to use CGContext but got no result, any idea to help? Thanks.

UIGraphicsBeginImageContext(mapView.bounds.size)
    let context : CGContext = UIGraphicsGetCurrentContext()!
    context.addLines(between: [CGPoint(x:oldX,y:oldY), CGPoint(x:newX, y:newY)])
    context.setStrokeColorSpace(CGColorSpaceCreateDeviceRGB())
    context.setStrokeColor(UIColor.blue.cgColor.components!)
    context.setLineWidth(3)
    mapView?.image?.draw(at: CGPoint(x:0, y:0))
    context.strokePath()
    mapView.image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
Taichi Kato
  • 602
  • 9
  • 24

1 Answers1

6

One option is to add a sub view to your image view and add the line drawing code into its draw(_ rect: CGRect) method.

A sample playground implementation:

class LineView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(white: 0.0, alpha: 0.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.blue.cgColor)
            context.setLineWidth(3)
            context.beginPath()
            context.move(to: CGPoint(x: 5.0, y: 5.0)) // This would be oldX, oldY
            context.addLine(to: CGPoint(x: 50.0, y: 50.0)) // This would be newX, newY
            context.strokePath()
        }
    }
}


let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png")) // This would be your mapView, here I am just using a random image
let lineView = LineView(frame: imageView.frame)
imageView.addSubview(lineView)
Jozef Legény
  • 1,157
  • 1
  • 11
  • 26
  • Thanks for your help , it is done. I have other question please : how can i delete these lines from the image ? tried removeFromSuperView but i have other view on the image with i do not want to delete it, thanks – mohammed HASSAN Dec 14 '16 at 12:48
  • for that you can use `lineView.removeFromSuperview()`, the other option is to control the draw function in the LineView to only display what you want. – Jozef Legény Dec 14 '16 at 12:57
  • Thank you very much , i tried to make it dynamic by sending points but i can not , please how to make it dynamic ? – mohammed HASSAN Dec 14 '16 at 13:51
  • Sorry but that is a much larger topic and too big for the Stack Overflow format. I would recommend reading up on iOS tutorials. – Jozef Legény Dec 14 '16 at 13:54