Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Image clipped to shape has transparent padding in context menu

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?

like image 719
Wilson Gramer Avatar asked Jul 02 '20 00:07

Wilson Gramer


1 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

like image 136
Wilson Gramer Avatar answered Nov 16 '22 00:11

Wilson Gramer