为tableview单元格图像创建圆形图片

时间:2017-02-27 23:54:57

标签: ios swift uiimage tableviewcell

我正在尝试在tableview单元格中制作图像循环,我已经在stackoverflow上看到了各种各样的方法,但这是我得到的最接近的:

Pics

正如你所看到的,它们看起来更像是圆圈而不是圆圈。在故事板中,我将约束设置为保持纵横比1:1和视图模式“纵横填充”。我正在使用这个UIImage扩展来形成圆形:

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!
  }
}

这就是我的cellForRowAt IndexPath的外观:

  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

不确定为什么他们不是完美的圈子,任何想法?

2 个答案:

答案 0 :(得分:1)

这是实现这种效果的一种非常高效的方式,因为您每次都要创建cornerRadius并将其渲染到单独的图像上下文中。

要快速简便地执行此操作,只需在actorProfileImage内为CastCell视图图层设置england <- c("London", "North East", "East of England", "West Midlands", "South East", "North West", "East Midlands", "South West", "Yorkshire and The Humber") Outlets2016_local$Region[Outlets2016_local$Region %in% england] <- "England" area_c <- factor(Outlets2016_local$Region, levels = c("England", "Scotland", "Wales"), labels = c("England", "Scotland", "Wales")) 属性。

答案 1 :(得分:0)

通过不使用扩展名,而是将其添加到cellForRowAtIndexPath,图像显示为圆形

 cell.actorProfileImage.layer.cornerRadius = cell.actorProfileImage.frame.size.height/2
  cell.actorProfileImage.clipsToBounds = true
  cell.actorProfileImage.layer.masksToBounds = true