首页 > 解决方案 > 在 React Native 中为不同的屏幕尺寸使用坐标?

问题描述

我有一个可拖动项目列表,其中包括一个位置 X 和一个位置 Y 以及一个名称。问题是,如果我将坐标保存在 Iphone 11 上,然后在 Ipad 上显示坐标,它看起来就像一团糟。所以我想知道如何保存/获取坐标以便我可以在不同尺寸的屏幕上使用这些坐标?

这是我的可拖动项目和我设置项目位置的功能。

  const [data, setData] = useState(mydata);


  const setItemPosition = (key, x, y) => {
    const updatedData = [...data];
    const item = data[key];
    item.X = x;
    item.Y = y;
    updatedData[key] = item;
    setData(updatedData);
  };

            {data.map((item, key) => (
              <Draggable
                x={10}
                y={200}
                key={key}
                renderColor="blue"
                renderSize={50}
                onShortPressRelease={() => setModalVisiblePlayer(true)}
                isCircle
                textcolor="#000000"
                renderText={() => {setItemName(key, name)}}
                onDragRelease={e => {
                  setItemPosition(
                    key,
                    e.nativeEvent.pageX,
                    e.nativeEvent.pageY,
                  );
                }}
              />
            ))}

标签: react-nativecoordinatesdraggable

解决方案


我有一个类似的用例,其中 x/y 坐标从一个用户发送到另一个用户以显示在屏幕上,每个用户可能具有唯一的屏幕尺寸。我使用下面的函数将传入的 x/y 转换为当前用户的当前 x/y。

let getRealCoords = useCallback((coords) => {
  // coords are the incoming x/y and the sending users' canvas/screen size
  // coords = {
  //   canvasX,
  //   canvasY,
  //   canvasWidth,
  //   canvasHeight
  // }
  let realX = coords.canvasX * (dimensionsRef.current.width / coords.canvasWidth);
  let realY = coords.canvasY * (dimensionsRef.current.height / coords.canvasHeight);

  return { x: realX.round(), y: realY.round() };
}, [styles])

Number.prototype.round = function(decimals = 0) { return Number(Math.round(this + 'e' + decimals) + 'e-' + decimals) }

我对这个函数/计算很幸运,结果坐标或多或​​少已经死了。如果您需要有关如何使用此 getRealCoords 函数的更多文档,请告诉我!


推荐阅读