创建一个具有圆形底部边缘的UIView

时间:2019-04-19 12:57:23

标签: swift view rounded-corners

我要对此视图进行四舍五入enter image description here

1 个答案:

答案 0 :(得分:1)

我认为这真的很接近您想要的:

rectView是您的初始视图; 您可以使用四边形曲线高度的+ 50来调整曲线

let rectView = UIView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
    rectView.backgroundColor = .red
    view.addSubview(rectView)

    let arcBezierPath = UIBezierPath()
    arcBezierPath.move(to: CGPoint(x: 0, y: rectView.frame.height))
    arcBezierPath.addQuadCurve(to: CGPoint(x: rectView.frame.width, y: rectView.frame.height), controlPoint: CGPoint(x: rectView.frame.width / 2 , y: rectView.frame.height + 50 ))
    arcBezierPath.close()

    let shapeLayer = CAShapeLayer()

    shapeLayer.path = arcBezierPath.cgPath

    shapeLayer.fillColor = UIColor.red.cgColor

    rectView.layer.insertSublayer(shapeLayer, at: 0)
    rectView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    rectView.layer.cornerRadius = 10
    rectView.layer.shadowRadius = 3
    rectView.layer.shadowColor = UIColor.black.cgColor
    rectView.layer.shadowOffset = CGSize(width: 0, height: 0)
    rectView.layer.shadowOpacity = 0.25

也许,甚至更好:  您可以创建视图:

let rectView = UIView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
view.addSubview(rectView)

扩展UIView

extension UIView {
    func addBottomArc(ofHeight height: CGFloat, topCornerRadius: CGFloat) {
       let arcBezierPath = UIBezierPath()
       arcBezierPath.move(to: CGPoint(x: 0, y: frame.height))
       arcBezierPath.addQuadCurve(to: CGPoint(x: frame.width, y: frame.height), controlPoint: CGPoint(x: frame.width / 2 , y: frame.height + height ))
       arcBezierPath.close()

       let shapeLayer = CAShapeLayer()

       shapeLayer.path = arcBezierPath.cgPath
       shapeLayer.fillColor = UIColor.red.cgColor

       layer.insertSublayer(shapeLayer, at: 0)
       layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
       layer.cornerRadius = topCornerRadius
    }
}

因此您可以像这样设置高度和拐角半径:

rectView.addBottomArc(ofHeight: 50, topCornerRadius: 15)

,然后将所需的阴影添加到视图中:

    rectView.layer.shadowRadius = 3
    rectView.layer.shadowColor = UIColor.black.cgColor
    rectView.layer.shadowOffset = CGSize(width: 0, height: 0)
    rectView.layer.shadowOpacity = 0.25