创建一个拉伸的半圆

时间:2018-11-01 08:00:50

标签: ios swift

我正在尝试创建一个uiview,其中顶部有一个拉伸的半圆。我已经想出了在下面裁剪一个半圆的方法,但是我似乎无法弄清楚如何使其像下面的图所示那样变小。

在这里,您会看到一个灰色图像,其中裁剪了一个较小的半圆:

enter image description here

到目前为止的代码:

    let path = UIBezierPath()
    path.move(to: bounds.origin)
    let center = CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y)
    path.addArc(withCenter: center, radius: bounds.size.width / 2.0, startAngle: .pi, endAngle: 0, clockwise: false)
    path.addLine(to: CGPoint(x: bounds.origin.x + bounds.size.width, y: bounds.origin.y))
    path.addLine(to: CGPoint(x: bounds.origin.x + bounds.size.width, y: bounds.origin.y + bounds.size.height))
    path.addLine(to: CGPoint(x: bounds.origin.x, y: bounds.origin.y + bounds.size.height))
    path.close()

    let mask = CAShapeLayer()
    mask.path = path.cgPath

    layer.mask = mask

3 个答案:

答案 0 :(得分:1)

尝试

func addParabolaWithMax()  {
    let path = UIBezierPath()

    let p0 = CGPoint(x: 0, y: 0)
    let p2 = CGPoint(x: self.view.frame.size.width/2, y: 100)

    let p1 = CGPoint(x: self.view.frame.size.width, y: 0)

    path.move(to: p1)
    path.addQuadCurve(to: p0, controlPoint: p2)

    path.lineWidth = 1
    path.stroke()
    let line = CAShapeLayer()
    line.path = path.cgPath;
    line.strokeColor = UIColor.black.cgColor
    line.fillColor = UIColor.blue.cgColor
    view.layer.addSublayer(line)
}

enter image description here

答案 1 :(得分:0)

class SampleViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.backgroundColor = UIColor.blue
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        setMask(control: CGPoint(x: 40.0, y: 100.0))
    }

    func setMask(control: CGPoint) {
        let bounds = view.bounds
        let path = UIBezierPath()
        path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
        path.addLine(to: bounds.origin)
        let control2 = CGPoint(x: bounds.maxX - control.x, y: control.y)
        path.addCurve(to: CGPoint(x: bounds.maxX, y: bounds.minY), controlPoint1: control, controlPoint2: control2)
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        path.close()
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        view.layer.mask = mask

    }
}

通过调整控制点,您可以更改曲率(iPhone X的模拟器屏幕截图,因此是圆角!)。

enter image description here

答案 2 :(得分:0)

由于我似乎只能将单个图像发布到答案,因此,这是控制点在贝塞尔曲线中的工作方式,以及如何通过调整控制点来更改曲线的弧度:

enter image description here

C2就是bounds.max - C1.x, C1.y