table 视图单元格 swift 中的圆形图像

circular image in table view cell swift

我正在尝试在 table 视图的每一行中创建一些圆形图像。我已经按照教程进行操作,但我的图像变成了菱形而不是圆形。我做错了什么:

 var cellImage = UIImage(named: pic)
 cell.imageView!.image = cellImage
 cell.imageView!.layer.frame = CGRectMake(0, 0, 190, 190)
 cell.imageView!.layer.borderWidth = 0.5
 cell.imageView!.layer.masksToBounds = false
 cell.imageView!.layer.borderColor = UIColor.blueColor().CGColor

 cell.imageView!.layer.cornerRadius = cell.imageView!.layer.frame.height/2
 cell.imageView!.clipsToBounds = true

如果您要创建自己的 imageView,最好在自定义 TableViewCell 中设置 cornerRadius。

class CircularTableViewCell: UITableViewCell {
@IBOutlet weak var circularImageView: UIImageView!
override func layoutSubviews() {
    circularImageView.layer.cornerRadius = circularImageView.bounds.height / 2
    circularImageView.clipsToBounds = true
}

}

注意 cornerRadius 属性 不能保证视图绝对是圆的,除非你将 imageView 的宽高比设置为 1:1。另一种创建圆形视图的方法是使用蒙版。

public extension UIView {
public func round() {
    let width = bounds.width < bounds.height ? bounds.width : bounds.height
    let mask = CAShapeLayer()
    mask.path = UIBezierPath(ovalInRect: CGRectMake(bounds.midX - width / 2, bounds.midY - width / 2, width, width)).CGPath
    self.layer.mask = mask
}

}

这将允许您使用任何 UIView 调用 round() 并确保视图始终是圆形的。例如

class CircularTableViewCell: UITableViewCell {
@IBOutlet weak var circularImageView: UIImageView!
override func layoutSubviews() {
   circularImageView.round()
}

}

尝试将静态值(宽度或高度的一半)作为角 radius.This 可能会解决您的问题。