CAShapeLayer 未出现在图层子视图上

CAShapeLayer not appearing on layer subview

我正在两点之间画一条线,但视图上没有显示任何内容。我搜索了其他 s/o 个问题,但似乎找不到解决方案。

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

试试这个代码:在 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)
}

创建一个swift文件并在UIView中将其命名为ShapeView.swiftclass并添加以下代码。

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

输出:

你的问题似乎和我的一样:你忘了在末尾添加这些行:

shapeLayer.stroke()
shapeLayer.fill()