LoginSignup
8
7

More than 5 years have passed since last update.

UITableViewCellに画像を表示する際にKingfisherを使って出来るだけ最適化する

Posted at

円形に画像を表示したい場合、UIImageViewのcornerRadiusをつけるとCoreGraphicsにメインスレッドで触れてセルの生成が遅くなる可能性があるので画像をそれっぽい感じに先に加工しておくとスクロールのスムーズさに貢献出来る(と思う)

KingfisherにはImageProcessorという機能があり、非同期に取得した画像を加工して表示することが出来る。
例えば円形に表示したい時はこんな感じ


extension Kingfisher where Base: ImageView {
  @discardableResult
  public func setCircleMaskedImage(with resource: Resource?,
                                   placeholder: Placeholder? = nil,
                                   options: KingfisherOptionsInfo? = nil,
                       progressBlock: DownloadProgressBlock? = nil,
                       completionHandler: CompletionHandler? = nil) -> RetrieveImageTask {
    let scale = UIScreen.main.scale
    let size = base.bounds.size.applying(CGAffineTransform(scaleX: scale, y: scale))
    let resizing = ResizingImageProcessor(referenceSize: size, mode: .aspectFill)
    let roundCorner = RoundCornerImageProcessor(cornerRadius: size.width / 2.0,
                                                targetSize: size,
                                                roundingCorners: .all,
                                                backgroundColor: base.backgroundColor)
    let imageProcess = DefaultImageProcessor().append(another: resizing).append(another: roundCorner)
    let items: KingfisherOptionsInfo = [.processor(imageProcess)]
    return setImage(with: resource,
                    placeholder: placeholder,
                    options: items + (options ?? []),
                    progressBlock: progressBlock,
                    completionHandler: completionHandler)
  }
}

のextensionを書いて
imageView.setCircleMaskedImage(with: url)と呼べばOK
UIScreen.main.scaleに関してはメインスレッドで呼ぶ必要があるので必要に応じてキャッシュしておくと良さそう。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7