Ios 为tableview单元格图像创建圆形图片
我尝试在tableview单元格中使图像循环,我在stackoverflow上看到了各种方法,但这是我得到的最接近的方法: 正如你所看到的,它们看起来更像是省略号而不是圆。在故事板中,我将约束设置为保持纵横比为1:1和视图模式纵横比填充。我将此UIImage扩展用于圆形:Ios 为tableview单元格图像创建圆形图片,ios,swift,uiimage,tableviewcell,Ios,Swift,Uiimage,Tableviewcell,我尝试在tableview单元格中使图像循环,我在stackoverflow上看到了各种方法,但这是我得到的最接近的方法: 正如你所看到的,它们看起来更像是省略号而不是圆。在故事板中,我将约束设置为保持纵横比为1:1和视图模式纵横比填充。我将此UIImage扩展用于圆形: extension UIImage { var circleMask: UIImage { let square = CGSize(width: min(size.width, size.height), heig
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 Indexath的外观:
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
不知道为什么它们不是完美的圆,知道吗?这是实现这种效果的一种非常不实用的方法,因为每次都要创建UIImageView并将其渲染到单独的图像上下文中
要快速简便地完成此操作,只需在CastCell内为actorProfileImage视图的层设置cornerRadius属性。通过不使用扩展名,而是将其添加到cellForRowAtIndexPath,图像显示为圆形
cell.actorProfileImage.layer.cornerRadius = cell.actorProfileImage.frame.size.height/2
cell.actorProfileImage.clipsToBounds = true
cell.actorProfileImage.layer.masksToBounds = true
试过了,它只是让它看起来像是带圆形边缘的正方形。对不起,我意识到我之前的评论不对,所以我把它删除了。顺便说一句,你有没有试过这个:?你确定只有在布局完成后才会调用circleMask吗?@AnthonyKong成功了,谢谢!