Libra Studio Log

開発に関することやゲーム、ガジェットなどについてつらつらと書き記しています

UIViewの指定した箇所を角丸にする

f:id:daihase:20190809100049p:plain

こんばんは、daihaseです。 今日は久々のSwiftネタを。というか久々のブログを。

UIViewの指定した箇所を角丸にする方法。 例えば全体を角丸にするには

let roundedView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        roundedView.layer.cornerRadius = 15
        roundedView.backgroundColor = .blue
        view.addSubview(roundedView)

こんな感じにしてやればなりますね。

でも左上だけ、とか右上だけ、といった箇所を指定する場合はちょっとした処理を書いてやらないといけません。それが以下。

UIViewを拡張したクラスを作ってやります。

import UIKit

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
        
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        
        self.layer.mask = maskLayer
    }
}

 

ではこれを使って作成したUIViewの指定した箇所を角丸にして表示してみましょう。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }
    
    private func setupView() {
        // 左上を角丸
        let roundedView1: UIView = {
            let v = UIView(frame: CGRect(x: (view.bounds.width - 100) / 2, y: 100, width: 100, height: 50))
            v.roundCorners([.topLeft], radius: 15.0)
            v.backgroundColor = .red
            return v
        }()
        // 左上と右上を角丸
        let roundedView2: UIView = {
            let v = UIView(frame: CGRect(x: (view.bounds.width - 100) / 2, y: 200, width: 100, height: 50))
            v.roundCorners([.topLeft, .topRight], radius: 15.0)
            v.backgroundColor = .red
            return v
        }()
        // 左上と右上と右下を角丸
        let roundedView3: UIView = {
            let v = UIView(frame: CGRect(x: (view.bounds.width - 100) / 2, y: 300, width: 100, height: 50))
            v.roundCorners([.topLeft, .topRight, .bottomRight], radius: 15.0)
            v.backgroundColor = .red
            return v
        }()
        // 左上と右上と右下と左下を角丸
        let roundedView4: UIView = {
            let v = UIView(frame: CGRect(x: (view.bounds.width - 100) / 2, y: 400, width: 100, height: 50))
            v.roundCorners([.topLeft, .topRight, .bottomRight, .bottomLeft], radius: 15.0)
            v.backgroundColor = .red
            return v
        }()
        
        [roundedView1, roundedView2, roundedView3, roundedView4].forEach {
            view.addSubview($0)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

 

ちなみにUIViewを拡張してるので当然UIButtonやUILabelも同じように指定した箇所を角丸化出来ます。

それでは良いSwift開発ライフを〜