简体   繁体   中英

How to set UIView in semi circle in Swift 5

I want to crop my UIView to the semi-circle and that will support all iPhone devices. Here, we can't set height and width to fix. I am using a multiplier.

Here is some of the SO answer I checked.

How to crop the UIView as semi circle?

Draw a semi-circle button iOS

It's work but for the fix height and width not with multiplier and I am targeting universal devices. Below is the image for semicircle UIView.

在此处输入图像描述

Thanks in advance.

I have just modified the circle code from this link code. The problem is in the original code it used the initial frame when again layoutSubviews method called at that time semiCirleLayer == nil this condition is prevented from the update bezier path.

class SemiCirleView: UIView {
    
    var semiCirleLayer: CAShapeLayer = CAShapeLayer()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let arcCenter = CGPoint(x: bounds.size.width / 2, y: bounds.size.height)
        let circleRadius = bounds.size.width / 2
        let circlePath = UIBezierPath(arcCenter: arcCenter, radius: circleRadius, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 2, clockwise: true)
        
        semiCirleLayer.path = circlePath.cgPath
        semiCirleLayer.fillColor = UIColor.red.cgColor
        
        semiCirleLayer.name = "RedCircleLayer"
        
        if !(layer.sublayers?.contains(where: {$0.name == "RedCircleLayer"}) ?? false) {
            layer.addSublayer(semiCirleLayer)
        }
        
        // Make the view color transparent
        backgroundColor = UIColor.clear
    }
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM