Balázs Vincze
Balázs Vincze

Reputation: 3832

UIView has different cornerRadius than CAShapeLayer

I want to add a background view to a UITableViewCell, and also a CAShapeLayer to act as a border around the background view (I will need a dashed border).

My problem is however, even though I set the cornerRadius of the view and the layer to the same value, they render completely differently.

enter image description here

Does anyone have a clue what's going on?

The code:

final class Cell: UITableViewCell {

    private let borderLayer = CAShapeLayer()
    private let _backgroundView = UIView()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // Add a blue background view.
        contentView.insertSubview(_backgroundView, at: 0)
        _backgroundView.backgroundColor = .blue
        _backgroundView.layer.cornerRadius = 28

        // Add the border layer.
        borderLayer.fillColor = nil
        borderLayer.strokeColor = UIColor.red.cgColor
        borderLayer.lineWidth = 2
        contentView.layer.addSublayer(borderLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Update the frames.
        _backgroundView.frame = contentView.bounds
        borderLayer.path = UIBezierPath(roundedRect: contentView.bounds, cornerRadius: _backgroundView.layer.cornerRadius).cgPath
    }
}

A Playground Gist to reproduce it

Any help is appreciated!

Upvotes: 1

Views: 351

Answers (2)

Balázs Vincze
Balázs Vincze

Reputation: 3832

Building the path from a CGPath directly seems to solve the problem.

borderLayer.path = CGPath(roundedRect: contentView.bounds, cornerWidth: _backgroundView.layer.cornerRadius,
                          cornerHeight: _backgroundView.layer.cornerRadius, transform:  nil)

Upvotes: 1

nwyyy
nwyyy

Reputation: 81

Seems like the calculation of corner radius is not consistent to UIBezierPath(roundedRect:, cornerRadius:).

How about an alternative approach??

Like:

_backgroundView.layer.borderWidth = 2
_backgroundView.layer.borderColor = UIColor.red.cgColor

Upvotes: 0

Related Questions