Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

circular image in table view cell swift

I am trying to create some a circular image in every row of my table view. I have followed tutorials but my image is turning out to be a diamond shape and 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
like image 363
user2363025 Avatar asked Jun 06 '15 16:06

user2363025


2 Answers

If you are creating your own imageView, it's better to set the cornerRadius inside the custom TableViewCell.

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

}

Note the cornerRadius property can't guarantee that the view will be absolutely round unless you set the imageView's width and height ratio to be 1:1. Another approach to create round view is using 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 the view is always round. e.g.

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

}

like image 51
Audrey Li Avatar answered Oct 10 '22 05:10

Audrey Li


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

like image 22
simardeep singh Avatar answered Oct 10 '22 05:10

simardeep singh