A circular image in a table cell

I am trying to create a circular image in every row of my table view. I followed textbooks, but my image got a diamond shape, not a circular one. What am I doing wrong:

 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
+4
source share
2 answers

If you are creating your own image, it is best to set cornerRadius inside a custom TableViewCell.

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

}

Please note that the cornerRadius property cannot guarantee that the presentation will be completely round unless you set the image width to height ratio to 1: 1. Another approach to creating a round look is to use a 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
}

}

This will allow you to call round () with any UIView and make sure that the view is always round. eg

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

}

+15

( ) . .

+1

All Articles