Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What is going on with this article?
@noppefoxwolf

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

More than 3 years have passed since last update.

円形に画像を表示したい場合、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に関してはメインスレッドで呼ぶ必要があるので必要に応じてキャッシュしておくと良さそう。

7
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
noppefoxwolf
きつねすき、にんげんこわい

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
7
Help us understand the problem. What is going on with this article?