【问题标题】:UIBezierPath: How to add a border around a view with rounded corners?UIBezierPath:如何在圆角视图周围添加边框?
【发布时间】:2015-08-16 03:50:54
【问题描述】:

我正在使用 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 的边框?

【问题讨论】:

  • 这真的不是那么容易 - 在我下面的回答中,我试图解决所涉及的不幸的微妙之处。
  • 嗨@gooberboobbutt!这么久了,你认为你能在我的回答上打勾吗!谢谢! :)
  • 你好 @gooberboobbutt - 为 2019 年提供完美的现代解决方案 :) 享受

标签: swift uibezierpath


【解决方案1】:

您可以重用 UIBezierPath 路径并向视图添加形状层。这是视图控制器内部的示例。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a view with red background for demonstration
        let v = UIView(frame: CGRectMake(0, 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, byRoundingCorners: .TopRight | .TopLeft, cornerRadii: CGSize(width: 25, 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 中的图层大小。

【讨论】:

  • path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.TopRight, .TopLeft], cornerRadii: CGSize(width: 25, height: 25)).CGPath
  • 这在细节上并不正确:你只看到一半的边界。
  • @hennes 你好吗...我在下面提出了一个完美的现代解决方案作为新答案!希望对您有所帮助!
【解决方案2】:

如上所说:

要完美做到这一点并不容易。

这是一个插入式解决方案。


这个

  • 正确解决了您绘制一半边界线的问题

  • 在自动布局中完全可用

  • 当视图的大小改变或动画

    时完全重新工作
  • 完全是 IBDesignable - 您可以在故事板中实时看到它

2019 年 ...

@IBDesignable
class RoundedCornersAndTrueBorder: UIView {
    @IBInspectable var cornerRadius: CGFloat = 10 {
        didSet { setup() }
    }
    @IBInspectable var borderColor: UIColor = UIColor.black {
        didSet { setup() }
    }
    @IBInspectable var trueBorderWidth: CGFloat = 2.0 {
        didSet { setup() }
    }
    
    override func layoutSubviews() {
        setup()
    }
    
    var border:CAShapeLayer? = nil
    
    func setup() {
        // make a path with round corners
        let path = UIBezierPath(
          roundedRect: self.bounds, cornerRadius:cornerRadius)
        
        // note that it is >exactly< the size of the whole view
        
        // mask the whole view to that shape
        // note that you will ALSO be masking the border we'll draw below
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        
        // add another layer, which will be the border as such
        
        if (border == nil) {
            border = CAShapeLayer()
            self.layer.addSublayer(border!)
        }
        // IN SOME APPROACHES YOU would INSET THE FRAME
        // of the border-drawing layer by the width of the border
        // border.frame = bounds.insetBy(dx: borderWidth, dy: borderWidth)
        // so that when you draw the line, ALL of the WIDTH of the line
        // DOES fall within the actual mask.
        
        // here, we will draw the border-line LITERALLY ON THE EDGE
        // of the path. that means >HALF< THE LINE will be INSIDE
        // the path and HALF THE LINE WILL BE OUTSIDE the path
        border!.frame = bounds
        let pathUsingCorrectInsetIfAny =
          UIBezierPath(roundedRect: border!.bounds, cornerRadius:cornerRadius)
        
        border!.path = pathUsingCorrectInsetIfAny.cgPath
        border!.fillColor = UIColor.clear.cgColor
        
        // the following is not what you want:
        // it results in "half-missing corners"
        // (note however, sometimes you do use this approach):
        //border.borderColor = borderColor.cgColor
        //border.borderWidth = borderWidth
        
        // this approach will indeed be "inside" the path:
        border!.strokeColor = borderColor.cgColor
        border!.lineWidth = trueBorderWidth * 2.0
        // HALF THE LINE will be INSIDE the path and HALF THE LINE
        // WILL BE OUTSIDE the path. so MAKE IT >>TWICE AS THICK<<
        // as requested by the consumer class.
        
    }
}

就是这样。


cmets中问题的初学者帮助...

  1. 制作一个名为“Fattie.swift”的“新 Swift 文件”。 (注意,有趣的是,它实际上并没有什么不同。如果您处于“不知道如何制作新文件”的阶段,请寻求基本的 Xcode 教程。)

  2. 将以上所有代码放入文件中

  3. 您刚刚为您的项目添加了一个“RoundedCornersAndTrueBorder”类。

  4. 在你的故事板上。将普通 UIView 添加到您的场景中。事实上,让它成为任何大小/形状,任何你喜欢的东西。

  5. 查看身份检查器。 (如果您不知道那是什么,请寻求基本教程。)只需将类更改为“RoundedCornersAndTrueBorder”。 (一旦你开始输入“Roun...”,它就会猜出你指的是哪个类。

  6. 您已完成 - 运行项目。

请注意,当然,您必须向 UIView 添加完整且正确的约束,就像您在 Xcode 中所做的任何事情一样。尽情享受吧!

类似的解决方案:

https://stackoverflow.com/a/57465440/294884 - 图像 + 圆角 + 阴影
https://stackoverflow.com/a/41553784/294884 - 两个角问题
https://stackoverflow.com/a/59092828/294884 - “阴影 + 孔”或“发光盒”问题
https://stackoverflow.com/a/57400842/294884 - “边框” AND 间隙”问题
https://stackoverflow.com/a/57514286/294884 - 基本的“添加”贝塞尔曲线

另请参阅下面的替代答案! :)

【讨论】:

  • 我们如何使用它来创建边框?对不起,如果我的问题太天真了。 :-/
  • 嘿@Fattie,非常感谢您的详细解释。好吧,我比那要好一些。但是,再次感谢您花时间帮助我。当然,这将对更多人有所帮助。但是,我来找的原因是不同的。我有一个需要边框的 UITextView,但我不想使用可用的方法。这可能吗?
  • 我想这就是经验!我试图做一个解决方法,你就像,“就这样做”。惊人的!谢谢。但是,我暂时使用我的解决方案。给我一种特别的感觉。但是,再次感谢!
  • 谢谢,这是唯一适用于 XCode 9.2 beta 的解决方案。
  • @MugeCevik - 你好 - 我提出了一个更好、更新的解决方案作为新答案
【解决方案3】:

绝对完美的2019解决方案

事不宜迟,这就是你如何做到这一点。

  1. 实际上不要使用视图附带的“基本”层
  2. 仅为图像创建一个新层。您现在可以(循环地)屏蔽它而不影响下一层
  3. 为边框创建一个新图层。它不会被图片层掩盖。

关键事实是

  1. 使用 CALayer,您确实可以应用 .mask 它只影响该层
  2. 在绘制圆(或任何边框)时,必须非常小心地注意您只能得到“宽度的一半” - 简而言之,从不裁剪使用您绘制的相同路径。
  3. 请注意,原始猫图像与水平黄色箭头一样宽。您必须小心地绘制图像,以便 整个 图像出现在圆形中,小于 整体自定义控件。

所以,按照通常的方式进行设置

import UIKit

@IBDesignable class GreenCirclePerson: UIView {
    
    @IBInspectable var borderColor: UIColor = UIColor.black { didSet { setup() } }
    @IBInspectable var trueBorderThickness: CGFloat = 2.0 { didSet { setup() } }
    @IBInspectable var trueGapThickness: CGFloat = 2.0 { didSet { setup() } }
    
    @IBInspectable var picture: UIImage? = nil { didSet { setup() } }
    
    override func layoutSubviews() { setup() }
    
    var imageLayer: CALayer? = nil
    var border: CAShapeLayer? = nil
    
    func setup() {
        
        if (imageLayer == nil) {
            imageLayer = CALayer()
            self.layer.addSublayer(imageLayer!)
        }
        if (border == nil) {
            border = CAShapeLayer()
            self.layer.addSublayer(border!)
        }
        

现在仔细为圆形裁剪图像制作图层:

        // the ultimate size of our custom control:
        let box = self.bounds.aspectFit()
        
        let totalInsetOnAnyOneSide = trueBorderThickness + trueGapThickness
        
        let boxInWhichImageSits = box.inset(by:
           UIEdgeInsets(top: totalInsetOnAnyOneSide, left: totalInsetOnAnyOneSide,
           bottom: totalInsetOnAnyOneSide, right: totalInsetOnAnyOneSide))
        
        // just a note. that version of inset#by is much clearer than the
        // confusing dx/dy variant, so best to use that one
        
        imageLayer!.frame = boxInWhichImageSits
        imageLayer!.contents = picture?.cgImage
        imageLayer?.contentsGravity = .resizeAspectFill
        
        let halfImageSize = boxInWhichImageSits.width / 2.0
        
        let maskPath = UIBezierPath(roundedRect: imageLayer!.bounds,
           cornerRadius:halfImageSize)
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        imageLayer!.mask = maskLayer
        

接下来作为一个完全独立的图层,随意绘制边框:

        // now create the border
        
        border!.frame = bounds
        
        // To draw the border, you must inset it by half the width of the border,
        // otherwise you'll be drawing only half the border. (Indeed, as an additional
        // subtle problem you are clipping rather than rendering the outside edge.)
        
        let halfWidth = trueBorderThickness / 2.0
        let borderCenterlineBox = box.inset(by:
            UIEdgeInsets(top: halfWidth, left: halfWidth,
            bottom: halfWidth, right: halfWidth))
        
        let halfBorderBoxSize = borderCenterlineBox.width / 2.0
        
        let borderPath = UIBezierPath(roundedRect: borderCenterlineBox,
          cornerRadius:halfBorderBoxSize)
        
        border!.path = borderPath.cgPath
        border!.fillColor = UIColor.clear.cgColor
        
        border!.strokeColor = borderColor.cgColor
        border!.lineWidth = trueBorderThickness
    }
}

一切都像在 iOS 标准控件中一样完美运行:

一切看不见的东西都是看不见的;可以看透整体自定义控件到后面的任何材质,没有“半厚”问题或缺少图像材质,可以按照通常的方式设置自定义控件背景颜色等。检查器控件都可以正常工作。 (呼!)

类似的解决方案:

https://stackoverflow.com/a/57465440/294884 - 图像 + 圆角 + 阴影
https://stackoverflow.com/a/41553784/294884 - 两个角问题
https://stackoverflow.com/a/59092828/294884 - “阴影 + 孔”或“发光盒”问题
https://stackoverflow.com/a/57400842/294884 - “边界” AND 间隙”问题
https://stackoverflow.com/a/57514286/294884 - 基本的“添加”贝塞尔曲线

【讨论】:

    【解决方案4】:

    肯定有!每个视图都有一个layer 属性(您可以通过给图层圆角来了解该属性)。 layer 上的另外两个属性是 borderColor 和 borderWidth。只需设置这些,您就可以为视图添加边框! (边框将跟随圆角。)请务必使用UIColor.CGColor 代替borderColor,因为普通的UIColor 与类型不匹配。

    【讨论】:

    • 如何将其添加到代码中?我一直在拔头发试图弄清楚。
    • 我知道那是什么感觉! rectShape.borderWidth = 3 和 rectShape.borderColor = UIColor.greenColor().CGColor 应该可以做到这一点!
    • 但我看到你已经这样做了。一个简单的解决方法是让绿卡内的图像更小一点。
    • 顶部是 uiimage,底部是标签,因此无法正常工作
    • 您是否考虑过将 UIImage 和 UILabel 作为子视图添加到容器 UIView 中?这样,您可以使 UIImage 的宽度比包含视图小一点,并将标签放置在视图内。绕过视图的角落,给它一个边框,然后你就可以开始了。如果您对如何执行此操作有任何疑问,请告诉我!
    【解决方案5】:
    **use this extension for round borders and corner**
    
    
    
           
           
        
     extension UIView {
    
       func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
        
        func roundCornersWithBorder(corners: UIRectCorner, radius: CGFloat) {
            let maskLayer = CAShapeLayer()
            maskLayer.frame = bounds
            maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius)).cgPath
            
            layer.mask = maskLayer
            
            // Add border
            let borderLayer = CAShapeLayer()
            borderLayer.path = maskLayer.path // Reuse the Bezier path
            borderLayer.fillColor = UIColor.clear.cgColor
            borderLayer.strokeColor = UIColor(red:3/255, green:33/255, blue:70/255, alpha: 0.15).cgColor
            borderLayer.lineWidth = 2
            borderLayer.frame = bounds
            layer.addSublayer(borderLayer)
        }
        
    }
    

    这样使用

    myView.roundCornersWithBorder(corners: [.topLeft, .topRight], radius: 8.0)

    myView.roundCorners(角:[.topLeft,.topRight],半径:8.0)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2015-04-26
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多