一个非常简单的视图:
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>
);
}
所以我只是用 width=371 和 height=477 创建一个视图,然后记录它的布局。当我在我的实际 iPhone 5s 设备上使用 expo 运行它时,我得到以下输出:
{
"layout": Object {
"height": 477,
"width": 371,
"x": 0,
"y": 0,
},
"target": 3,
}
这是正确的。但是,当我在屏幕尺寸为 1080x1920:420dpi 的 android pixel 2 模拟器上运行它时(我没有实际的 android 设备),我得到以下输出:
Object {
"layout": Object {
"height": 476.952392578125,
"width": 371.047607421875,
"x": 0,
"y": 0,
},
"target": 3,
}
所以宽度和高度略有不同。通常我会说这并不重要,因为它不到一个像素,但问题是,对于我的应用程序,这似乎会导致看起来非常难看的显示错误,其中一些应该无缝地组合在一起的图块有一些非常小边距:
实际上我不能百分百确定这是否是原因。然而,在我看来,它是一个非常可疑的候选人。知道如何解决这个问题吗?
编辑:
一些更多细节来重现图像中的像素插值错误。正如我所说,这篇文章中描述的问题对我来说似乎是导致这种情况的原因,但我不确定。然而,在所有情况下,上述场景都非常奇怪。
因此对于以下代码(应无缝添加在一起的 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>
);
}
我在 android 和 ios 上得到这个输出:
然后我可以例如通过使用元素检查器中的 expo 构建(或者使用上面的日志记录方法)来验证问题是否发生,即 1. 容器的大小不完全正确,而且我注意到一些网格单元也没有正确的大小,你可以在这些使用元素检查器的截图中看到:
答案 0 :(得分:3)
尝试简单地将像素四舍五入为整数。例如通过:
Math.round()
或者您可以使用 PixelRatio.roundToNearestPixel(number)
react-native
方法
答案 1 :(得分:2)
您看到的这些小偏移是由于不同的设备具有不同的像素密度。换句话说,它们每平方英寸的像素数量不同。
当您指定宽度/高度的绝对值时,RN 将捕捉到最近的像素以避免产生模糊的视觉效果,如果您试图产生完美的网格,这可能不是您想要的。
为避免这种情况,您可以将单元格大小四舍五入到最接近的像素。在上面的例子中,它看起来像这样:
import {PixelRatio} from 'react-native';
const cell_size = PixelRatio.roundToNearestPixel(53);
您可以阅读有关 PixelRatio
here 的更多信息。