swift中的光滑圆角

问题描述 投票:0回答:4

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

这是一个比较:

如何快速切换它?

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

ios swift rounded-corners
4个回答
36
投票

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

sampleButton.layer.cornerCurve = .continuous

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

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


29
投票

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)
)

来源


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)

2
投票

对于 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: x, style: .continuous))
    }
}

Result here

© www.soinside.com 2019 - 2024. All rights reserved.