Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a circle UIView in Swift

The following code works on an iPhone but on an iPad the circle is not evenly rounded.

How can I make the view look like a circle on both devices?

let width:CGFloat = UIScreen.main.bounds.width*0.0533      
label.layer.masksToBounds = true
label.layer.cornerRadius = width/2

enter image description here

like image 557
tolerate_Me_Thx Avatar asked Nov 07 '17 08:11

tolerate_Me_Thx


People also ask

How do I make a circle in iOS Swift?

Enter Swift as Language and choose Storyboard as User Interface, Choose Next. Select File -> New File -> iOS -> Cocoa Touch Class. Name the class CircleView with a subclass of UIView. This class will contain the views where the circles will be drawn.


2 Answers

If you want your UIView to appear as a circle there are couple of ways doing this.

  • Set it's corner radius to half of the width/height (most common way)

If you don't know the height/width of your view in advance. You can simply override layoutSubviews() function in it's superview class or func viewDidLayoutSubviews() function in view controller and set the corner radius directly there.

override func layoutSubviews() {
  super.layoutSubviews()
  label.layer.cornerRadius = label.frame.size.width/2
}

Don't forget to set the UIView's layer's masksToBounds property to true.

  • Set mask layer

Specify bezier path for the mask layer. Layer's frame must be updated every time the view changes its size.

  • Rounding images

If you're dealing with images, you can also consider rounding the image itself before displaying it in UIImageView - performance wise it could be a way faster than the previous options.

like image 120
deathhorse Avatar answered Oct 21 '22 09:10

deathhorse


For making complete circle, you should keep height and width same for your label. Use this code.

let width:CGFloat = UIScreen.main.bounds.width*0.0533  
label.frame = CGRect(0,0,width,width)    
label.layer.masksToBounds = true
label.layer.cornerRadius = width/2
like image 33
DJ_Mobi90 Avatar answered Oct 21 '22 08:10

DJ_Mobi90