我想在image中画一个包围猴子脸的边界框,坐标如下:
64,111
347,111,
64,304,
347,304
这是所需的外观:
我使用resizeMode
= contain
显示图像,这会导致边界框错位和大小错误。
我认为矩形的左上角应该是64,111(使用绝对位置),宽度和高度应该正好是两点之间的差值(width = 283和height = 193)。我知道由于图像没有以其完整的高度和宽度显示,所以我需要相应地缩小边界框。然而,我无法计算图像调整大小后的最终大小。我如何计算才能正确显示边界框?当我这样使用onLayout时:
onLayout={(event) => {
const {x, y, width, height} = event.nativeEvent.layout;
}}
高度总是不正确的,因为它包括其图像和背景的总高度(当我所有我需要的是图像本身的高度)
下面是我的代码:https://snack.expo.dev/@melampus123/forlorn-raisins
1条答案
按热度按时间5n0oy7gb1#
这比预期的要难,因为正如你所说,
onLayout
不包括图像被缩小的大小。我以为onLoad也会缩小图像,但那是不可能的。所以我想知道缩小大小的唯一方法就是自己重新计算。如果你知道原始图像的大小,以及它将被包含到的视图的大小,你就可以做到这一点。使用图像大小挂钩:
视图大小钩子(我实际上经常使用钩子,所以它在 typescript 中)
将所有功能整合在一起:
Demo