如何将UIView裁剪为半圆?

Gan*_*kam 4 uiview uibezierpath swift

我想以半圆形状裁剪UIView

喜欢这个图像

提前致谢.

Gab*_*ves 6

这个问题已在这里得到解答:画一个半圆形按钮iOS

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

斯威夫特3

let myView = [this should be your view]
let circlePath = UIBezierPath(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
Run Code Online (Sandbox Code Playgroud)

斯威夫特4

let myView = [this should be your view]
let circlePath = UIBezierPath(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
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助你


Law*_*iet 6

一种方便的方法就是子类a 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
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)