Post

Replies

Boosts

Views

Activity

Reply to CPListItem Image
I've tried the suggested solutions above but they either didn't work for me or deemed to be to overly complex to handle the matter. I've managed to solve it using fairly rudimentary scaling: extension CarServicesItemDTO {   func toListItem() -> CPListItem {     let listItem = CPListItem(text: title, detailText: subtitle)     DispatchQueue.global(qos: .background).async {       let imgUrl = URL(string: imageUrl)       if let imageUrl = imgUrl {         let data = try? Data(contentsOf: imageUrl)         if let imageData = data {           let image = UIImage(data: imageData)?.scalePreservingAspectRatio(targetSize: CPListItem.maximumImageSize) ?? UIImage()           listItem.setImage(image)         }       }     }     return listItem   } } extension UIImage {   func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {       // Determine the scale factor that preserves aspect ratio       let widthRatio = targetSize.width / size.width       let heightRatio = targetSize.height / size.height       let scaleFactor = min(widthRatio, heightRatio)       // Compute the new image size that preserves aspect ratio       let scaledImageSize = CGSize(         width: size.width * scaleFactor,         height: size.height * scaleFactor       )       // Draw and return the resized UIImage       let renderer = UIGraphicsImageRenderer(         size: scaledImageSize       )       let scaledImage = renderer.image { _ in         self.draw(in: CGRect(           origin: .zero,           size: scaledImageSize         ))       }       return scaledImage     } } CarServiceItemDTO is a simple data type containing the data fields received from backend, and using toListItem() it will be converted into a CPListItem. The scaling happens in scalePreservingAspectRatio() and is an algorithm borrowed from this StackOverflow answer: https://stackoverflow.com/a/71078857
Nov ’22