React Native:Android 未正确设置宽度和高度 []

man*_*zet 5 android ios react-native expo

一个非常简单的视图:

import React from "react";
import { View } from "react-native";

export default function App() {
  return (
    <View
      onLayout={(layout) => {
        console.log(layout.nativeEvent);
      }}
      style={{
        width: 371,
        height: 477,
      }}
    ></View>
  );
}
Run Code Online (Sandbox Code Playgroud)

所以我只是制作一个宽度=371高度=477 的视图,然后记录其布局。当我在实际的 iPhone 5s 设备上使用 expo 运行此命令时,我得到以下输出:

import React from "react";
import { View } from "react-native";

export default function App() {
  return (
    <View
      onLayout={(layout) => {
        console.log(layout.nativeEvent);
      }}
      style={{
        width: 371,
        height: 477,
      }}
    ></View>
  );
}
Run Code Online (Sandbox Code Playgroud)

哪个是对的。但是当我在屏幕尺寸为 1080x1920:420dpi 的 Android Pixel 2 模拟器上运行它时(我没有实际的 Android 设备),我得到以下输出:

{
  "layout": Object {
    "height": 477,
    "width": 371,
    "x": 0,
    "y": 0,
  },
  "target": 3,
}
Run Code Online (Sandbox Code Playgroud)

所以宽度和高度是稍微的。通常我会说这并不重要,因为它不到一个像素,但问题是,对于我的应用程序来说,这似乎会导致非常难看的显示错误,其中一些应该无缝拼接在一起的图块有一些非常小的利润:

在此输入图像描述

事实上,我不能百分百确定是否是这个原因。然而,在我看来,这是一个非常可疑的候选人。知道如何解决这个问题吗?

编辑:

重现图像中像素插值误差的更多细节。正如我所说,这篇文章中描述的问题对我来说似乎是导致此问题的原因,但我不能百分百确定。然而,在所有情况下,上述情况都非常奇怪。

因此,对于以下代码(应无缝添加在一起的 7x9 53 像素大视图网格):

import React from "react";
import { View } from "react-native";

export default function App() {
  let cell_size = 53;
  let width = 7;
  let height = 9;

  let rows = [];
  for (let i = 0; i < height; i++) {
    let row_elms = [];
    for (let j = 0; j < width; j++) {
      row_elms.push(
        <View
          key={"key" + j + "_" + i}
          style={{
            width: cell_size,
            height: cell_size,
            backgroundColor: "white",
          }}
        ></View>
      );
    }
    rows.push(
      <View
        key={"row" + i}
        style={{
          width: cell_size * width,
          height: cell_size,
          flexDirection: "row",
        }}
      >
        {row_elms}
      </View>
    );
  }

  return (
    <View
      style={{
        justifyContent: "center",
        alignItems: "center",
        height: "100%",
        width: "100%",
        backgroundColor: "black",
      }}
    >
      <View style={{ width: cell_size * width, height: cell_size * height }}>
        {rows}
      </View>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

我在 android 和 ios 上得到这个输出:

在此输入图像描述

例如,我可以通过使用元素检查器中的 expo 构建(或者使用上面的日志记录方法)来验证问题是否发生,即 1. 容器不完全具有正确的大小,而且我还注意到一些网格单元也没有正确的大小,正如您在我使用元素检查器的屏幕截图中看到的那样: 在此输入图像描述

Art*_*tal 4

您看到的这些小偏移是由于不同设备具有不同的像素密度所致。换句话说,它们每平方英寸的像素数量不同。

当您指定宽度/高度的绝对值时,RN 将捕捉到最近的像素以避免产生模糊的视觉效果,如果您试图生成完美的网格,这可能不是您想要的。

为了避免这种情况,您可以将像元大小四舍五入到最接近的像素。在上面的例子中,它看起来像这样:

import {PixelRatio} from 'react-native';    
const cell_size = PixelRatio.roundToNearestPixel(53);
Run Code Online (Sandbox Code Playgroud)

您可以PixelRatio 在此处阅读更多相关信息。