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

时间:2015-06-06 16:29:04

标签: ios image swift cornerradius

我正在尝试在表格视图的每一行中创建一些圆形图像。我已经按照教程,但我的形象是钻石形状,而不是圆形。我做错了什么:

 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

2 个答案:

答案 0 :(得分: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
}

}

请注意,除非将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
}

}

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

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

}

答案 1 :(得分:1)

Try giving the static value(half of width or height) as corner radius.This may solve your problem.