使图像在 swift 中变圆?

Make images round in swift?

我正在尝试制作圆形图片,但出于某种原因,以下代码创建了菱形照片:

    profilePicture.layer.cornerRadius = profilePicture.frame.size.width / 2
    profilePicture.clipsToBounds = true

如何让它变圆?谢谢!

您可能遗漏了一些东西,下面的代码适合我:

            profilePicture.layer.borderWidth=1.0
            profilePicture.layer.masksToBounds = false
            profilePicture.layer.borderColor = UIColor.whiteColor().CGColor
            profilePicture.layer.cornerRadius = profilePicture.frame.size.height/2
            profilePicture.clipsToBounds = true

注意:要获得完美的圆形,图像视图框架应为正方形。

它显示菱形,因为您在视图大小更改之前设置了 cornerRadius。

这将导致菱形:

var myView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
myView.backgroundColor = UIColor.redColor()
view.addSubview(myView)
myView.layer.cornerRadius = myView.frame.size.width / 2
// setting frame doesn't change corner radius from the former large value
myView.frame = CGRect(x: 50, y: 50, width: 50, height: 50)

您可以在 viewWillAppear:

中在显示视图之前立即进行设置

要获得圆形的任何 UIImageview,您需要先将其框架设置为方形。例如,如果您 UIImageView 有 Frame(20,20,100,100),请看高度和宽度相同。然后,您需要将 UIImageviewcornerradius 属性设置为 halfheight 或 [=20] 的大小=]宽度 .

我在 Xamarin.iOS 中做了类似的事情:-

 imageView.Layer.CornerRadius = imageView.Frame.Size.Width / 2;
 imageView.ClipsToBounds = true; 

尝试一下它对我有用,我刚刚添加了一个 self.在命令之前

    self.profilePicture.frame.size.width / 2;
    self.profilePicture.clipsToBounds = true;

希望它有用:)