Search code examples
iosuicollectionviewuicollectionviewcelluilistcontentconfiguration

How to provide retina sized image for UIListContentConfiguration?


When using UIListContentConfiguration, how do you provide a retina sized image? I see the cell’s image view is sized based on the size of the image you provide. Imagine I want to display a thumbnail photo fetched from some URL for example in a 28x28pt square (similar to an album in the Photos app’s sidebar), so the image needs to be 56x56px to prevent pixelation on 2x iPads. But this causes the image view in the cell to be 44x44pt because it seemingly tried to make it 56x56pt but the cell isn’t tall enough so it maxed out at the cell height.

let rowRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, SidebarItem> { (cell, indexPath, item) in
    let thumbnailSize = CGSize(width: 28 * UIScreen.main.scale, height: 28 * UIScreen.main.scale)

    var contentConfiguration = UIListContentConfiguration.sidebarCell()
    contentConfiguration.text = item.title
    contentConfiguration.image = downloadedImage.preparingThumbnail(of: thumbnailSize)
    cell.contentConfiguration = contentConfiguration

    // downloadedImage is an image downloaded from some url, it could be any size like 100x100 for example
    // need to resize it to create a 56x56px image on a 2x screen, intended to be displayed in a 28x28pt image view
}

Desired screenshot Actual screenshot


Solution

  • I found out the image's scale needs to match the display scale for the image view to be sized correctly in the cell. If you have a 56x56px 1x image you want to display at 28x28pt on a 2x display, you can create a new image that sets the scale like so:

    let thumbnailImage = downloadedImage.preparingThumbnail(of: thumbnailSize) //56x56px @ 1x displays in 56x56pt image view
    let scaledThumbnailImage = UIImage(cgImage: thumbnailImage.cgImage!, scale: UIScreen.main.scale, orientation: thumbnailImage.imageOrientation) //56x56px @2x displays in 28x28pt image view