Home > Back-end >  How to have a UIView with line corners instead of rounded corners in the bottom
How to have a UIView with line corners instead of rounded corners in the bottom

Time:12-25

enter image description here

I want to create a UIView with this shape that has line corners. How can I draw that with UIBezierPath or is there an easier way to do so? Any help would be very appreciated!

CodePudding user response:

Yes, you should probably create a path that draws that shape.

Probably the most processor-efficient way to do that would be to install a CAShapeLayer into the view as a sublayer, and install a path into the shape layer's path property. Consider the following playground:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    let shapeLayer = CAShapeLayer()
    let dogEarValue: CGFloat = 40.0

    func buildShape() {
        let box = view.bounds
        shapeLayer.frame = box

        let path = UIBezierPath()
        path.move(to: box.origin)
        path.addLine(to: CGPoint(x:box.maxX, y: box.origin.y))
        path.addLine(to: CGPoint(x:box.maxX, y: box.maxY - dogEarValue))
        path.addLine(to: CGPoint(x:box.maxX - dogEarValue, y: box.maxY))
        path.addLine(to: CGPoint(x:box.origin.x   dogEarValue, y: box.maxY))
        path.addLine(to: CGPoint(x:box.origin.x, y: box.maxY - dogEarValue))
        path.close()
        shapeLayer.path = path.cgPath
    }

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        shapeLayer.fillColor = UIColor.black.cgColor
        shapeLayer.backgroundColor = UIColor.clear.cgColor
        view.layer.addSublayer(shapeLayer)

        let label = UILabel()
        label.text = "Hello World"
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black


        view.addSubview(label)
        self.view = view
    }

    override func viewDidLayoutSubviews() {
        buildShape()
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
  • Related