react-native - 在 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,
);
}}
/>
))}
解决方案
我有一个类似的用例,其中 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 函数的更多文档,请告诉我!
推荐阅读
- python - 大熊猫的双边 t 检验
- javascript - 如何描述一个可以正确序列化的值?
- html - 如何在链接弹簧启动/角度应用程序中获取 th:href="@{}" 而不是 href=""
- c++ - 当分母超出 unsigned long long int 范围时如何使用模?
- c++ - 递归函数的问题(检查一个数字是否是一个完美的平方)
- c# - 使用 ML.Net 为集群 ID 分配标签
- javascript - 尝试使用 node.js 将二维数组插入 sql server 数据库
- r - 如何在 R 中使用 Keras 从深度学习中获得平衡的准确性?
- php - 从 php 文件运行 shell 脚本无法在 CWD 之外创建/写入/删除文件
- reactjs - 覆盖 Reactstrap 进度条的屏幕阅读器