【问题标题】:UICollectionViewCell - Round Downloaded ImageUICollectionViewCell - 圆形下载图像
【发布时间】:2023-03-15 15:58:01
【问题描述】:

我正在尝试使用我使用 KingFisher(图像缓存库)获得的圆形图像设置一个 collectionView。

我不确定应该用圆角、imageView 还是单元格本身设置什么。即使单元格是圆形的,图像似乎也填满了正方形。

到目前为止,我正在使用此代码(如果我在将图像更改为正方形后未设置它):

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
if let path = user.profilePictureURL {
                    if let url = URL(string: path) {
                        cell.profilePictureImageView.kf.setImage(with: url)
                        cell.profilePictureImageView.layer.cornerRadius = cell.profilePictureImageView.frame.width/2.0
                    }
                }     

还有 ImageView :

class ProfilePicture : UIImageView {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    func commonInit(){
        self.layer.masksToBounds = false
        self.layer.cornerRadius = self.layer.frame.width/2.0
        self.clipsToBounds = true
    }
}

但是第一次下载的图片是这样的(单元格背景是蓝色的)

【问题讨论】:

    标签: ios swift uiimageview uicollectionview kingfisher


    【解决方案1】:

    你可以这样使用:

    extension UIImageView {
    
       func setRounded() {
          let radius = CGRectGetWidth(self.frame) / 2
          self.layer.cornerRadius = radius
          self.layer.masksToBounds = true
       }
    }
    

    然后调用如下方法:

    imageView.setRounded()
    

    【讨论】:

    • 我什至在图像缓存库(Kingfisher)的回调上调用这个,但我仍然是同样的错误。 (不是在所有单元格上,似乎是随机的)
    【解决方案2】:

    你可以通过调整高度(纵向)而不是宽度来得到一个圆圈:

    self.layer.cornerRadius = self.layer.frame.height/2.0
    

    如果您对结果不满意,则必须调整 contentMode.scaleAspect。通过调整长边可以得到一个圆圈,但您不会看到整个图像。

    【讨论】:

      【解决方案3】:

      可以在图片中得到一个带有 UIView 扩展名的圆圈

      extension UIImage {
      var circleMask: UIImage {
          let square = size.width < size.height ? CGSize(width: size.width, height: size.width) : CGSize(width: size.height, height: size.height)
          let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
          imageView.contentMode = UIView.ContentMode.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!
      }}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 2012-12-13
        • 2021-03-17
        相关资源
        最近更新 更多