koj*_*ow7 8 screen-orientation react-native imagebackground
即使我可以更改屏幕方向以更新状态并重新渲染,ImageBackground 组件仍然不会更新其宽度。
我有以下代码:
<View
onLayout={event => this.mylayoutchange(event)}
style={{ flex: 1, backgroundColor: 'green' }}
>
<ImageBackground
style={{ flex: 1, width: this.state.width, height: this.state.height }}
imageStyle={{ resizeMode: 'repeat' }}
source={require('../assets/images/my_background.jpg')}
>
<View>
<Text>.... Other code here....</Text>
</View>
</ImageBackground>
</View>;
Run Code Online (Sandbox Code Playgroud)
当用户改变设备的方向时, mylayoutchange() 函数被调用。它正确更新状态。渲染函数将更新。宽度和高度已正确更改,如 中所示console.log()
。但是,无论出于何种原因,<ImageBackground>
都不会更新其正确的宽度和高度。
当屏幕旋转时,背景图像不再填满屏幕的整个尺寸,而是看到绿色背景颜色。
我究竟做错了什么?
我的环境:
"react": "16.13.1",
"react-native": "0.63.2",
Run Code Online (Sandbox Code Playgroud)
您需要使用resize
forresizeMethod
以使图像获得实际调整大小:
当图像的尺寸与图像视图的尺寸不同时应该用于调整图像大小的机制。默认为
auto
.
auto
:使用试探法在resize
和之间进行选择scale
。
resize
:一种软件操作,它在解码之前更改内存中的编码图像。scale
当图像比视图大得多时,应该使用它。
scale
:图像被缩小或放大。与 相比resize
,scale
速度更快(通常是硬件加速)并生成更高质量的图像。如果图像小于视图,则应使用此选项。如果图像比视图稍大,也应该使用它。
很明显,RN 选择scale
了您的情况,因此您必须明确将其设置resize
为在方向更改和 flex 样式更改开始时才能工作:
return (
<View
style={{ flex: 1, backgroundColor: 'blue' }}
>
<ImageBackground
// All props other than children, style, imageStyle, imageRef,
// will be passed to the inner Image component,
// so, we can use resizeMethod that will be passed to the Image component
resizeMethod="resize"
style={{
flex: 1,
borderWidth: 1,
borderColor: 'red'
}}
imageStyle={{
resizeMode: 'repeat',
}}
source={require('../assets/images/my_background.jpg')}
>
<View>
<Text style={{
backgroundColor: 'white'
}}>.... Other code here....</Text>
</View>
<View style={{
position: 'absolute',
right: 0,
bottom: 0
}}>
<Text style={{
backgroundColor: 'white'
}}>Absolute bottom-right text</Text>
</View>
</ImageBackground>
</View>
);
Run Code Online (Sandbox Code Playgroud)
"react": "16.13.1",
"react-native": "0.63.2",
Run Code Online (Sandbox Code Playgroud)
用于重复背景的示例图块图像(400 X 400 像素):
归档时间: |
|
查看次数: |
774 次 |
最近记录: |