smooth rounded corners in swift

匆匆过客 提交于 2020-07-04 05:51:49

问题


How can I create a UIButton with rounded corners that are smooth? The standard apple rounded corners are much nicer than the standard rounded corners. If I design a button in sketch, I can toggle "smooth corners" which toggles the corners of a shape from Apple rounded corners (smooth) to standard rounded corners.

Here is a comparison:

How can I toggle this in swift?

showContentButton.layer.cornerRadius = 20 rounds the corners, however, I don't really know if this rounded corners are "smooth corners" or "standard rounded corners". And I don't know how to toggle this. Any ideas?


回答1:


Starting iOS 13.0, you can just use this property in addition to setting the cornerRadius:

sampleButton.layer.cornerCurve = .continuous

This is also easily animatable, which previously resulted in problems using a UIBezierPath.

See more at https://developer.apple.com/documentation/quartzcore/calayer/3152596-cornercurve




回答2:


Prior to iOS 13

To get that effect you can use UIBezierPath

Edit: Usage in UIView

class MyView: UIView {

    let myButton UIButton = UIButton()

    override func layoutSubviews() {
        super.layoutSubviews()

        // your roundPath code here
    }

}

Edit 2:

Use this approach for rounding specific corners:

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

Source




回答3:


Just use this extension

extension CALayer {

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

}

and use it like this

cell.layer.roundCorners(radius: 18)


来源:https://stackoverflow.com/questions/52310339/smooth-rounded-corners-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!