SwiftUI Image clipped to shape has transparent padding in context menu

Viewed 1439

In my SwiftUI app, I have an image in my asset catalog with an aspect ratio of 1:1. In my code, I have an Image view with a different aspect ratio that clips the image to the new size:

Image("My Image")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 300, height: 250)
    .clipped()

image clipped to aspect ratio

But when I attach a context menu to this image (with the contextMenu modifier), the original aspect ratio is still there, but with transparent padding:

image clipped to aspect ratio with context menu

How do I keep the image clipped to the new frame inside the context menu, so there's no padding?

2 Answers

On iOS 15, please see the accepted post. This solution works on iOS 14.


I was able to solve this by adding a .contentShape(Rectangle()) modifier to the image:

Image("My Image")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 300, height: 250)
    .clipped()
    .contentShape(Rectangle())
    .contextMenu {
        Text("Menu Item")
    }

image clipped to aspect ratio with context menu - correct behavior

I believe the correct solution that will work in all scenarios is to set the first argument (kind) in the contentShape:

func contentShape<S>(_ kind: ContentShapeKinds, _ shape: S)

Set that to .contextMenuPreview and this will work for all shapes:

Image("leaf")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 300, height: 300)
    .clipShape(Circle())
    .contentShape(ContentShapeKinds.contextMenuPreview, Circle())
    .contextMenu {
        Text("Menu Item")
    }

enter image description here

Related