如何在Swift中创建一个圆圈UIView

tol*_*Thx 4 cornerradius ios swift

以下代码适用于iPhone,但在iPad上,圆圈不均匀.

如何在两台设备上使视图看起来像一个圆圈?

let width:CGFloat = UIScreen.main.bounds.width*0.0533      
label.layer.masksToBounds = true
label.layer.cornerRadius = width/2
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 6

要制作完整的圆形,您应该保持标签的高度和宽度相同.使用此代码.

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
Run Code Online (Sandbox Code Playgroud)


dea*_*rse 5

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
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将UIView的图层的masksToBounds属性设置为true。

  • 设置遮罩层

指定遮罩层的贝塞尔曲线路径。每次视图更改大小时,都必须更新图层的框架。

  • 取整图像

如果要处理图像,则还可以考虑在将图像本身舍入之前在UIImageView中显示图像本身-在性能方面,它可能比以前的选项要快。