首页 > 解决方案 > UIView 的cornerRadius 与 CAShapeLayer 不同

问题描述

我想在 a 中添加一个背景视图UITableViewCell,并且还要将 aCAShapeLayer作为背景视图的边框(我需要一个虚线边框)。

然而,我的问题是,即使我将视图的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
    }
}

重现它的游乐场 Gist

任何帮助表示赞赏!

标签: iosswiftuiviewrounded-cornerscashapelayer

解决方案


直接从 CGPath 构建路径似乎可以解决问题。

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

推荐阅读