代码之家  ›  专栏  ›  技术社区  ›  Ganesh Manickam Gil

如何将UIView裁剪为半圆?

  •  6
  • Ganesh Manickam Gil  · 技术社区  · 7 年前

    我想将UIView裁剪为半圆形状

    like this image

    3 回复  |  直到 6 年前
        1
  •  8
  •   Lawliet    7 年前

    一种方便的方法就是子类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
            }
        }    
    }
    
        2
  •  6
  •   dahiya_boy    5 年前

    Draw a semi-circle button iOS

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

    Swift 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
    

    Swift 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
    

    我希望这对你有帮助

        3
  •  3
  •   azeem usmani    4 年前

    让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