【问题标题】:Working with coordinates in React native for different screen sizes?在 React Native 中为不同的屏幕尺寸使用坐标?
【发布时间】:2021-10-08 07:54:23
【问题描述】:

我有一个可拖动项目列表,其中包括一个位置 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-native coordinates draggable


    【解决方案1】:

    我有一个类似的用例,其中 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 函数的更多文档,请告诉我!

    【讨论】:

    • 非常感谢,看起来不错!明天我会试试这个代码:)
    • 您好@t_killah,是否可以获得更多文档? :D
    • 它相当简单/即插即用。传递一个包含传入的 x、y 和传入用户画布的高度/宽度的对象,用当前用户画布的宽度/高度替换 dimensionsRef.current.width/height 并享受。 Number.prototype.round 只是一个辅助函数,用于四舍五入到某个小数位。
    猜你喜欢
    • 2023-04-02
    • 2023-03-31
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多