在 Swift 中尝试制作圆形 UIView 时出错

Error trying to make a circular UIView in Swift

我的屏幕布局中有一个 UIImageView,它会根据容器视图尺寸动态调整大小。我想在圆形视图中转换它,我正在使用以下代码:

let dSize: CGFloat = min(imageview.frame.height, imageview.frame.width)
imageview.frame = CGRectMake(0, 0, dSize, dSize)
imageview.clipsToBounds = true
imageview.layer.cornerRadius = dSize/2.0
imageview.layer.borderWidth = 1.0
imageview.layer.borderColor = UIColor.whiteColor().CGColor

问题是生成的视图并不总是圆形的。为了达到效果,我必须在 iPhone 4 上将 dSize 除以 2.0,在 [=23= 上除以 1.7 ] 5/5s 和 1.5 在 iPhone 6/6s。我不知道我做错了什么。

viewDidLoad() 对于您的 UIImageView 上的几何图形来说还为时过早,请尝试 viewWillAppear(),因为这是保证几何图形可用的地方。

由于您使用的是自动布局,我建议将其粘贴到 viewDidLayoutSubviews()。每次发生自动布局时都会调用它。即使视图不改变方向,这也可能是多次。正如您在评论中指出的那样,确保在方法内部调用 super(您也应该对 viewDidLoad() 等视图控制器生命周期方法执行相同的操作)

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.addCircleBorderToImageView(self.imageView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.addCircleBorderToImageView(self.imageView)
}

// I made this UIView so it can be used with any view not just image views.
func addCircleBorderToImageView(imgView: UIView) {
    let dSize: CGFloat = min(imgView.frame.height, imgView.frame.width)
    imgView.bounds = CGRectMake(0, 0, dSize, dSize) // centered in container you want to use bounds over frame for this scenario
    imgView.clipsToBounds = true
    imgView.layer.cornerRadius = dSize/2.0
    imgView.layer.borderWidth = 1.0
    imgView.layer.borderColor = UIColor.whiteColor().CGColor
}

你能试试这个吗

//To make your imageView circular
imageView.layer.cornerRadius = imageView.frame.size.height/2;
imageView.layer.masksToBounds = YES;

//To add border
imageView.layer.borderColor = [UIColor whiteColor].CGColor;
imageView.layer.borderWidth = 2;