swift – UIBezierPath:如何在带圆角的视图周围添加边框?

我正在使用UIBezierPath让我的imageview有圆角,但我也想为imageview添加边框.请记住,顶部是uiimage,底部标签.

目前使用此代码生成

let rectShape = CAShapeLayer()
rectShape.bounds = myCell2.NewFeedImageView.frame
rectShape.position = myCell2.NewFeedImageView.center
rectShape.path = UIBezierPath(roundedRect: myCell2.NewFeedImageView.bounds,byRoundingCorners: .TopRight | .TopLeft,cornerRadii: CGSize(width: 25,height: 25)).CGPath
myCell2.NewFeedImageView.layer.mask = rectShape

我想为此添加绿色边框,但我无法使用

myCell2.NewFeedImageView.layer.borderWidth = 8
myCell2.NewFeedImageView.layer.borderColor = UIColor.greenColor().CGColor

因为它会切断边框的左上角和右上角,如下图所示:

有没有办法添加UIBezierPath边框和我当前的代码

您可以重用UIBezierPath路径并向视图添加形状图层.以下是视图控制器内的示例.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a view with red background for demonstration
        let v = UIView(frame: CGRectMake(0,100,100))
        v.center = view.center
        v.backgroundColor = UIColor.redColor()
        view.addSubview(v)

        // Add rounded corners
        let maskLayer = CAShapeLayer()
        maskLayer.frame = v.bounds
        maskLayer.path = UIBezierPath(roundedRect: v.bounds,height: 25)).CGPath
        v.layer.mask = maskLayer

        // Add border
        let borderLayer = CAShapeLayer()
        borderLayer.path = maskLayer.path // Reuse the Bezier path
        borderLayer.fillColor = UIColor.clearColor().CGColor
        borderLayer.strokeColor = UIColor.greenColor().CGColor
        borderLayer.linewidth = 5
        borderLayer.frame = v.bounds
        v.layer.addSublayer(borderLayer)   
    }

}

最终结果如下所示.

请注意,这仅在视图大小固定时按预期工作.当视图可以调整大小时,您需要创建自定义视图类并在layoutSubviews中调整图层大小.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...