Clipping a resized image using aspectRatio scaling SwiftUI
13:18 01 May 2023

At the end of the day, I'm trying to scale to fill an image into a height of X (439px in my case) and then clip it using a RoundedRectangle.

post.picture
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(height: 439)
    .clipped()
    .clipShape(Circle())

This view is inside a VStack. If that is necessary to resolve this, I'll post it too, but I don't think it is.

post.picture is an Image property within the Post struct. It looks like this

struct Post: Hashable, Codable {
    var id: Int
    var userId: Int
    var location: String
    var activityId: Int
    var cheerCount: Int
    
    private var pictureLocation: String
    var picture: Image {
        let mainPath = "/hardcoded/path/"
        if let image = UIImage(contentsOfFile: "\(mainPath)/\(pictureLocation)") {
            return Image(uiImage: image)
        } else {
            return Image(systemName: "photo")
        }
    }
}

The code produces this

enter image description here

The issue is that the circle is cut off at the edges. I want the circle mask to be scaled down but the image to retain it's aspect ratio and size.

I am not sure how to do this. I'm using a clipShape(Circle()) to make the issue more clear but I really want to clip the image with RoundedRectangle.

The code works properly when the image height is larger than width, and cuts off the mask shape when the width larger than the height.

It's suppose to look like this

enter image description here

swift swiftui