我知道公式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
Run Code Online (Sandbox Code Playgroud)
有什么理由发生这种情况吗?这让我疯了!
更新为了清除混淆,UIImageView
在我的故事板中声明了190x190
它,因为它还1:1
应用了宽高比约束,以确保它保持比例宽度和高度.
更新2为了对我的自动布局约束产生任何疑虑,我附上了下面的图像,显示了为其设置的约束imgAvatar
.如您所见,宽度和高度匹配,AR设置为确保它保持1:1的比例.我希望能够解决任何进一步的疑虑
答案莱昂纳多指出了一个非常实用且可重复使用的解决方案来解决这个问题,使用Swift扩展可以确保给定的UIImage总是方形的,因此总是生成一个圆圈,我已经在下面发布了Leonardo的解决方案:
extension UIImage {
var circleMask: UIImage {
let square = size.width < size.height ? CGSize(width: size.width, height: size.width) : CGSize(width: size.height, height: size.height)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.borderColor …
Run Code Online (Sandbox Code Playgroud) 我有一个可以调用的子类UIView CircleView
.CircleView会自动将圆角半径设置为其宽度的一半,以使其成为圆形.
问题是当"CircleView"通过AutoLayout约束调整大小时......例如在设备轮换上 ......由于"cornerRadius"属性必须赶上,并且操作系统仅发送,因此在调整大小之前它会严重失真单个"边界"更改为视图的框架.
我想知道是否有人有一个好的,明确的策略来实现"CircleView"的方式在这种情况下不会扭曲,但仍然会将其内容掩盖为圆形并允许在所述UIView周围存在边框.
我有一个tableview
自定义单元格,storyboard
使用标识符构建AutoLayout
.
其中一个subviews
需要是圆形的(layer.cornerRadius = width/2)
,它在开始时是一个正方形.
我试过layoutSubviews()
但似乎在AutoLayout
改变它的大小之前调用它...同样的事情didMoveToSuperview()
在AutoLayout
更改了尺寸之后,将这样的内容更新到我的子视图的正确功能在哪里?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell_small") as! Cell
...
return cell
}
// In Cell
override func layoutSubviews() {
rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
rankLabel.layer.masksToBounds = true
}
override func didMoveToSuperview() {
rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
rankLabel.layer.masksToBounds = true
}
Run Code Online (Sandbox Code Playgroud)
结果: