在Swift中实现平滑圆角

29

如何创建一个带有圆角、光滑的UIButton?苹果标准的圆角比普通的圆角更好看。如果我在Sketch中设计了一个按钮,我可以切换“光滑边角”选项,从苹果圆角(光滑)切换到普通圆角。

以下是比较图:

enter image description here

在Swift中如何切换这个选项呢?

showContentButton.layer.cornerRadius = 20 可以将按钮的边角变为圆角,但我不确定这些圆角是“光滑的”还是“普通的”,也不知道如何进行切换。有什么建议吗?

4个回答

40

1
一个绝妙的答案! - Fattie

29

iOS 13之前

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

Smooth corners

编辑: 在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)
)

来源


1
你是在 layoutSubviews 方法里面做的吗? - inokey
1
该按钮只有一个圆角,但看起来像是一个平滑的角。而其他三个角都是锐角(90°)。 - WalterBeiter
1
最后一个问题:我如何将圆角限制在特定的角落?例如:右上角和右下角应该是圆角,但左上角和左下角应该是尖角。 - WalterBeiter
@WalterBeiter,我知道已经有一段时间了,但你能否接受这个答案呢? :) - inokey
3
@WalterBeiter,谢谢!我已添加备忘录,说明我的解决方案适用于iOS 13之前的版本。 - inokey
显示剩余6条评论

3

对于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


我认为应该给Nhat Nguyen Duc提供赏金。因为他的答案是这里最Swifty的。而且它不受任何全局属性更改的限制。 - Allan Garcia

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)

你不能这样添加CALayer。当你添加一个CALayer时,你需要在每次调用layoutSubviews时更新它的frame(这是layoutSubviews的整个目的)。 - Fattie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接