我想将背景视图添加到UITableViewCell
,还需要将CAShapeLayer
用作背景视图周围的边框(我需要一个虚线边框)。
但是,即使我将视图和图层的cornerRadius设置为相同的值,它们的呈现方式也完全不同。
有人知道发生了什么吗?
代码:
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
感谢您的任何帮助!
似乎拐角半径的计算与UIBezierPath(roundedRect :, cornerRadius :)不一致。
如何选择替代方法?
赞:
_backgroundView.layer.borderWidth = 2
_backgroundView.layer.borderColor = UIColor.red.cgColor
直接从CGPath构建路径似乎可以解决问题。
borderLayer.path = CGPath(roundedRect: contentView.bounds, cornerWidth: _backgroundView.layer.cornerRadius,
cornerHeight: _backgroundView.layer.cornerRadius, transform: nil)