【问题标题】:smooth rounded corners in swift快速平滑圆角
【发布时间】:2019-02-17 23:45:37
【问题描述】:

如何创建一个圆角平滑的 UIButton? 标准的苹果圆角比标准的圆角好得多。 如果我在草图中设计一个按钮,我可以切换“平滑角”,它将形状的角从 Apple 圆角(平滑)切换到标准圆角。

这是一个比较:

如何快速切换?

showContentButton.layer.cornerRadius = 20 圆角,但是,我真的不知道这个圆角是“圆角”还是“标准圆角”。而且我不知道如何切换它。有什么想法吗?

【问题讨论】:

    标签: ios swift rounded-corners


    【解决方案1】:

    iOS 13.0开始,除了设置cornerRadius,你可以只使用这个属性:

    sampleButton.layer.cornerCurve = .continuous
    

    这也很容易设置动画,以前使用 UIBezierPath 会导致问题。

    https://developer.apple.com/documentation/quartzcore/calayer/3152596-cornercurve查看更多信息

    【讨论】:

      【解决方案2】:

      iOS 13 之前的版本

      要获得这种效果,您可以使用UIBezierPath

      编辑: 在 UIView 中的使用

      class MyView: UIView {
      
          let myButton UIButton = UIButton()
      
          override func layoutSubviews() {
              super.layoutSubviews()
      
              // your roundPath code here
          }
      
      }
      

      编辑 2:

      使用此方法对特定角进行圆角:

      let roundPath = UIBezierPath(
          roundedRect: bounds,
          byRoundingCorners: [.topLeft, .topRight],
          cornerRadii: CGSize(width: 10, height: 10)
      )
      

      Source

      【讨论】:

      • 按钮完全消失了。我做到了:let smoothCornersRoundedPath = UIBezierPath(roundedRect: bounds, cornerRadius: 8) let maskLayer = CAShapeLayer() maskLayer.path = smoothCornersRoundedPath.cgPath showContentButton.layer.mask = maskLayer
      • 你是用layoutSubviews方法做的吗?
      • 按钮只有一个圆角。但它似乎是一个光滑的角落。但所有其他三个角都是尖锐的 (90°)
      • 最后一个问题:如何将拐角半径限制为特定拐角?例如:右上角和右下角应该是圆角,但左上角和左下角应该是锐利的。
      • @WalterBeiter 谢谢!我已经添加了我的解决方案早于 iOS 13 的备忘录。
      【解决方案3】:

      只需使用此扩展程序

      extension CALayer {
      
         func roundCorners(radius: CGFloat) {
             let roundPath = UIBezierPath(
                 roundedRect: self.bounds,
                 cornerRadius: radius)
             let maskLayer = CAShapeLayer()
             maskLayer.path = roundPath.cgPath
             self.mask = maskLayer
         }
      
      }
      

      并像这样使用它

      cell.layer.roundCorners(radius: 18)
      

      【讨论】:

        【解决方案4】:

        对于 SwiftUI,你可以试试这个:

        .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
        

        例子:

        Rectangle()
            .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
            .padding()
        

        或使用扩展:

        extension View {
            func smoothCornerRadius(_ x: CGFloat) -> some View {
                return self
                    .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
            }
        }
        

        Result here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-16
          • 1970-01-01
          相关资源
          最近更新 更多