5

I want to draw diagonal line with rounded corners in view. My code:

class DiagonalView: UIView {

// MARK: - Public Properties

@IBInspectable var fillColor: UIColor = UIColor.white {
    didSet {
        self.diagonalLayer.strokeColor = fillColor.cgColor
        self.redraw()
    }
}

@IBInspectable var lineWidth: CGFloat = 1 {
    didSet {
        self.diagonalLayer.lineWidth = lineWidth
        self.redraw()
    }
}

// MARK: - Private Properties

private var diagonalLayer: CAShapeLayer = {
    let layer = CAShapeLayer()
    layer.fillColor = UIColor.clear.cgColor
    layer.strokeColor = UIColor.white.cgColor
    layer.lineCap = kCALineCapRound
    layer.lineWidth = 1
    return layer
}()

// MARK: - Constructors

override func awakeFromNib() {
    super.awakeFromNib()
    self.layer.addSublayer(self.diagonalLayer)
    self.setupPath()
}

override func layoutSubviews() {
    super.layoutSubviews()
    self.setupPath()
}

// MARK: - Private methods

private func redraw() {
    self.setNeedsDisplay()
}

private func setupPath() {
    let startPoint = CGPoint(x: self.frame.width, y: 0)
    let endPoint = CGPoint(x: 0, y: self.frame.height)
    let path = UIBezierPath()
    path.move(to: startPoint)
    path.addLine(to: endPoint)
    path.close()
    self.diagonalLayer.path = path.cgPath
}

}

Line position is right. But corners are not rounded. Result:

enter image description here

The code looks good but think I mess something... Any suggestions?

Nirav D
  • 71,513
  • 12
  • 161
  • 183
RomanHouse
  • 2,552
  • 3
  • 23
  • 44
  • 1
    I haven't tried to do get rounded end-caps on a shape layer before. It seems strange that the shape layer has a line cap style separate from the path's line cap style. What if you set the line cap style to rounded on the CGPath that you install into your shape layer? – Duncan C Oct 07 '16 at 10:55

1 Answers1

5

I think I found the problem. The docs say:

The line cap style specifies the shape of the endpoints of an open path when stroked.

You are closing your path. Leave it open.

Duncan C
  • 128,072
  • 22
  • 173
  • 272