如何将UIView裁剪为半圆?

时间:2017-07-19 14:05:55

标签: swift uiview uibezierpath

我想以半圆形状裁剪UIView

like this image

提前致谢。

3 个答案:

答案 0 :(得分:5)

此问题已在此处得到解答:Draw a semi-circle button iOS

这是该问题的摘录,但使用的是UIView:

Swift 3

let myView = [this should be your view]
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: myView.bounds.size.width / 2, y: 0), radius: myView.bounds.size.height, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
myView.layer.mask = circleShape

Swift 4

let myView = [this should be your view]
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: myView.bounds.size.width / 2, y: 0), radius: myView.bounds.size.height, startAngle: 0.0, endAngle: .pi, clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
myView.layer.mask = circleShape

我希望这有助于你

答案 1 :(得分:5)

一种方便的方法就是将UIView作为子类,在其上添加一个图层,如果不是默认情况下,则使视图颜色透明。

import UIKit

class SemiCirleView: UIView {

    var semiCirleLayer: CAShapeLayer!

    override func layoutSubviews() {
        super.layoutSubviews()

        if semiCirleLayer == nil {
            let arcCenter = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
            let circleRadius = bounds.size.width / 2
            let circlePath = UIBezierPath(arcCenter: arcCenter, radius: circleRadius, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 2, clockwise: true)

            semiCirleLayer = CAShapeLayer()
            semiCirleLayer.path = circlePath.cgPath
            semiCirleLayer.fillColor = UIColor.red.cgColor
            layer.addSublayer(semiCirleLayer)

            // Make the view color transparent
            backgroundColor = UIColor.clear
        }
    }    
}

答案 2 :(得分:1)

此问题的处理速度为Swift 4和Swift 5。

let yourView =(是您要从顶部裁剪半圆的视图)

 let circlePath = UIBezierPath(arcCenter: CGPoint(x: yourView.bounds.size.width / 2, y: yourView.bounds.size.height), radius: yourView.bounds.size.height, startAngle: 0.0, endAngle: .pi, clockwise: false)
    let circleShape = CAShapeLayer()
    circleShape.path = circlePath.cgPath
    yourView.layer.mask = circleShape