我知道公式frame.size.width/2
应该会生成一个圆形边框,但是在XCode中我目前遇到了一些差异。
我有两个测试设备(iPhone6和第五代iPod touch),同时我也有模拟器运行。我的两个设备都正确显示,但模拟器将我的圆绘制为圆角矩形:
我用来实现这个效果的代码(虽然非常简单)是:
imgAvatar.layer.masksToBounds = true
imgAvatar.clipsToBounds = true
imgAvatar.layer.cornerRadius = imgAvatar.frame.size.width/2
imgAvatar.layer.borderWidth = 5
imgAvatar.layer.borderColor = UIColor.whiteColor().CGColor
这是发生的任何原因吗?它让我发疯了!
更新 为了消除混淆,UIImageView
在我的Storyboard中声明为190x190
,并且还应用了一个1:1
的纵横比约束,以确保它保持等比例的宽度和高度。
更新2 为了消除关于我的自动布局约束的任何怀疑,我已经附上了下面的图片,显示了imgAvatar
设定的约束。如您所见,宽度和高度相匹配,并且AR设置可以确保它保持那个1:1的比率。我希望这能解决任何进一步的疑虑。
答案 Leo指出了一个极其实用和可重复使用的解决方案来解决这个问题。使用Swift扩展,我们可以确保给定的UIImage始终是正方形的,从而始终生成一个圆形。我已经张贴了Leo的方案如下:
extension UIImage {
var circleMask: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: .init(origin: .init(x: 0, y: 0), size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 5
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
imgAvatar.image = yourImage.circleMask
imgFrame
以及生成的cornerRadius
属性吗?(注意,NSStringFromCGRect()
在这里可能会有帮助。) - Craig OtisviewDidLoad
太早了。视图控制器的视图尚未调整大小。尝试使用viewWillAppear:
。 - rmaddyviewWillAppear
,看到相同的结果。 - Halfpint