How to crop the UIView as semi circle?
Asked Answered
L

3

6

I want to crop UIView in semi circle shape

like this image

Thanks in advance.

Lashonda answered 19/7, 2017 at 14:5 Comment(2)
Show us what you have done so far.Kristiankristiansand
UIBezierPath could be a good solution.Wilma
C
8

A convenient way is just subclass a UIView, add a layer on it and make the view color transparent if it's not by default.

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
        }
    }    
}
Common answered 19/7, 2017 at 14:36 Comment(1)
Hii, Semi circle working fine but my UIView is on the bottom but when I add this class it shows me in the centre can you please help me? I want this on bottomHydroscope
L
6

This question was already answered here: Draw a semi-circle button iOS

This is a extract of that question but using a 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

I hope this helps you

Lungi answered 19/7, 2017 at 14:13 Comment(0)
U
3

it works in swift 4 and swift 5 for this issue.

let yourView = (is the view you want to crop semi circle from top)

 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
Uninhibited answered 29/11, 2019 at 19:55 Comment(1)
Bravo! https://developer.apple.com/documentation/uikit/uiview/1622557-maskPortative

© 2022 - 2024 — McMap. All rights reserved.