Search code examples
iosswiftcashapelayer

CAShapeLayer not appearing on layer subview


I am drawing a line between two points, but nothing is appearing on the view. I have search other s/o questions but can't seem to find a solution.

override func viewDidLoad() {
    super.viewDidLoad()
    self.drawLineFromPoint(point1: CGPoint(x: 10,y: 50), point2: CGPoint(x: 10,y: 80))
}


func drawLineFromPoint(point1:CGPoint, point2:CGPoint) {

    let path = UIBezierPath()
    path.move(to: point1)
    path.addLine(to: point2)

    let shapeLayer = CAShapeLayer()
    shapeLayer.bounds = CGRect(x: 100, y: 100, width: 100, height: 100)

    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 3
    shapeLayer.fillColor = UIColor.clear.cgColor
    self.view.layer.addSublayer(shapeLayer)
}

Solution

  • Try this code: tested in Swift 3.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        let shapeLayer = ShapeView(frame: CGRect(x: 100, y: 200, width: 100, height: 100), shape: 0)
        shapeLayer.backgroundColor = UIColor.clear
        shapeLayer.layer.borderWidth = 5
        shapeLayer.layer.borderColor = UIColor.red.cgColor
        view.addSubview(shapeLayer)
    }
    

    Create a swift file and name it ShapeView.swift in UIView class and add the following code.

    import UIKit
    
    class ShapeView: UIView {
    var currentShapeType: Int = 0
    
    init(frame: CGRect, shape: Int) {
        super.init(frame: frame)
        self.currentShapeType = shape
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     override func draw(_ rect: CGRect) {
    
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.beginPath()
        ctx?.move(to: CGPoint(x: 10.0, y: 50.0))
        ctx?.addLine(to: CGPoint(x: 10.0, y: 80.0))
       // ctx?.addLine(to: CGPoint(x: 100.0, y: 200.0))
        ctx?.setLineWidth(3)
        ctx?.closePath()
        ctx?.strokePath()     
    }   
    }
    

    Output:

    enter image description here