0

I'm trying to make images circular in a tableview cell, I've the various ways I've seen on stackoverflow but this is the closest I've gotten:

Pics

As you can see they look more like elipses than circles. In storyboard I have the constraints set to keeping the aspect ratio 1:1 and the view mode "aspect fill". I'm using this UIImage extension for the circular shape:

extension UIImage {
  var circleMask: UIImage {
    let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
    let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
    imageView.contentMode = UIViewContentMode.scaleAspectFill
    imageView.image = self
    imageView.layer.cornerRadius = square.width/2
    imageView.layer.borderColor = UIColor.white.cgColor
    imageView.layer.borderWidth = 5
    imageView.layer.masksToBounds = true
    UIGraphicsBeginImageContext(imageView.bounds.size)
    imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return result!
  }
}

This is how my cellForRowAt IndexPath looks:

  let cell = detailTableView.dequeueReusableCell(withIdentifier: castResuseIdentifier)
    as! CastCell

  let cast = castArray[indexPath.row]

  cell.actorName.text = cast.name
  cell.characterName.text = cast.character
  cell.actorProfileImage.image = castImageArray[indexPath.row].circleMask

  self.detailTableView.rowHeight = 100
  detailTableView.allowsSelection = true

  return cell

Not sure why they aren't perfect circles, any idea?

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

2 Answers2

1

That is a really non-performant way of achieving that effect, since you're creating a UIImageView and rendering it to a separate image context every time.

For a quick and easy way to do it, just set the cornerRadius property for the layer of the actorProfileImage view inside your CastCell.

Dave Weston
  • 6,527
  • 1
  • 29
  • 44
0

By not using the extension and instead adding this to the cellForRowAtIndexPath the images came out circular

 cell.actorProfileImage.layer.cornerRadius = cell.actorProfileImage.frame.size.height/2
  cell.actorProfileImage.clipsToBounds = true
  cell.actorProfileImage.layer.masksToBounds = true
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92