Swift 實現部分圓角

來源:互聯網
上載者:User

標籤:code   idt   eve   self   放棄   str   traints   簡單   pre   

圓角一直是開發中經常遇到的問題。

為了實現部分圓角的效果,我去查了一下用 OC 如何?。


 

可惜直接文法轉換以後是不能用的,因為 mas_maskContraints (是 Masonry 這個庫的文法,感謝isaced)方法在 Swift 中我並沒有找到。在 Stack Overflow 中的搜尋結果更加感人:


 

我最終放棄了,選擇了另一種實現:


 

把他用 Swift 的方式實現:

extension UIView {    /// 部分圓角    ///    /// - Parameters:    ///   - corners: 需要實現為圓角的角,可傳入多個    ///   - radii: 圓角半徑    func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))        let maskLayer = CAShapeLayer()        maskLayer.frame = self.bounds        maskLayer.path = maskPath.cgPath        self.layer.mask = maskLayer    }}

調用的時候需要注意一點:

// 調用沒有任何問題,將左上方與右上方設為圓角。button.corner(byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.topRight], radii: 5)// 編譯錯誤let corners = [UIRectCorner.topLeft, UIRectCorner.topRight]button.corner(byRoundingCorners: corners, radii: 5)

 

需要轉換一下類型:

let corners: UIRectCorner = [UIRectCorner.bottomLeft, UIRectCorner.bottomRight]// 類型可省略let corners: UIRectCorner = [.bottomLeft,.bottomRight]

UIBerizePath 類中,我們看到的 byRoundingCorners 參數接收的是一個 UIRectCorner ,並非數群組類型,所以需要做一步類型轉換,同時設定多個圓角。


 

在效能方面,我簡單做了個1000行圓角Button和Label的表格,滾動起來十分流暢。用instrument種的CoreAnimation測試,可能會產生離屏渲染。根據WWDC 2014: Advanced Graphics and Animations for iOS Apps,系統圓角使用 mask 的方式實現的,現在無論硬體效能還是最佳化肯定要比當年做的好。

 

Swift 實現部分圓角

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.