表视图细胞迅速的圆形图像

use*_*025 5 image cornerradius ios swift

我试图在我的表视图的每一行创建一个圆形图像.我已经按照教程,但我的形象是钻石形状,而不是圆形.我究竟做错了什么:

 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
Run Code Online (Sandbox Code Playgroud)

Aud*_* Li 17

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

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

}

请注意,除非将imageView的宽度和高度比设置为1:1,否则cornerRadius属性无法保证视图绝对是圆形的.另一种创建圆形视图的方法是使用Mask.

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
}
Run Code Online (Sandbox Code Playgroud)

}

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

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

}