9

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

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

裁剪为纵横比的图像

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

使用上下文菜单将图像裁剪为纵横比

如何将图像剪辑到上下文菜单内的新框架中,因此没有填充?

4

2 回答 2

13

在 iOS 15 上,请参阅已接受的帖子。此解决方案适用于 iOS 14。


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

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

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

于 2020-07-02T00:33:07.940 回答
1

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

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

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

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

在此处输入图像描述

于 2021-11-14T23:53:37.117 回答