裁剪为形状的 SwiftUI 图像在上下文菜单中具有透明填充

wgr*_*r03 9 ios swift swiftui ios14

在我的 SwiftUI 应用程序中,我的资产目录中有一个长宽比为 1:1 的图像。在我的代码中,我有一个Image具有不同纵横比的视图,可以将图像裁剪为新尺寸:

Image("My Image")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 300, height: 250)
    .clipped()
Run Code Online (Sandbox Code Playgroud)

图像裁剪为纵横比

但是当我将上下文菜单附加到该图像(使用contextMenu修饰符)时,原始纵横比仍然存在,但具有透明填充:

使用上下文菜单裁剪到纵横比的图像

如何将图像剪裁到上下文菜单内的新框架,以便没有填充?

ali*_*ego 13

我相信适用于所有场景的正确解决方案是在 contentShape 中设置第一个参数(种类):

func contentShape<S>(_ kind: ContentShapeKinds, _ shape: S)
Run Code Online (Sandbox Code Playgroud)

将其设置为 .contextMenuPreview 这将适用于所有形状:

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

在此输入图像描述


wgr*_*r03 11

我能够通过向.contentShape(Rectangle())图像添加修饰符来解决这个问题:

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

使用上下文菜单裁剪到纵横比的图像 - 正确的行为

  • 这是一个非常漂亮的解决方案。我还可以使用内容形状将上下文菜单预览更改为 Circle()。谢谢! (2认同)