Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop the UIView as semi circle?

I want to crop UIView in semi circle shape

like this image

Thanks in advance.

like image 387
Ganesh Manickam Avatar asked Jul 19 '17 14:07

Ganesh Manickam


2 Answers

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
        }
    }    
}
like image 139
Lawliet Avatar answered Sep 18 '22 22:09

Lawliet


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

like image 43
Gabriel Goncalves Avatar answered Sep 19 '22 22:09

Gabriel Goncalves