【发布时间】:2020-03-03 20:19:57
【问题描述】:
我有一个视图,它使用 Geometry Reader 来计算图像区域的大小:
GeometryReader { metrics in
ZStack{
self.image
.resizable()
.frame(width: (metrics.size.height - 10) * 0.561403509 , height: metrics.size.height - 10, alignment: .top)
.clipped()
}
}
但我有一个函数,我想使用 GeometryReader 计算的帧高度和宽度来裁剪图像。
我有一个单独的函数,可以在按下按钮时裁剪图像:
DownloadImageButton(prepareImagefunction: { self.prepareImage() })
然后调用 prepareImage 函数:
func prepareImage( ) {
// In order for image cropping to work, we need the equivalent of view.bounds in order to adjust the crop so that it correctly measures the crop area. We need metrics.width and metrics.height
var adjustmentScaleForDisplaySize = targetSize.width / metrics.width
请注意,GeometryReader 是调用 prepareImage 的父视图的子视图。因此,理想情况下,子节点会将指标值保存在 EnvironmentObject 或绑定到父节点中。
【问题讨论】:
-
您能否添加一个示例来说明您要完成的工作,即使它不起作用?
metric可以像任何其他变量一样传递给函数,但不清楚您要做什么。 -
感谢您的评论。我已经编辑了答案。当图像显示在屏幕上时,我需要保存 metrics.size 以便稍后在父视图的图像裁剪功能中使用它。如果您考虑图像裁剪,通常您使用 view.bounds 来确定裁剪区域。这是等效的要求。