添加全屏背景图像的最佳方法是什么

2022-08-30 02:03:11

我想向视图添加全屏图像,所以我编写此代码

return (
    <View style={styles.container}>
        <Image source={require('image!egg')}  style={styles.backgroundImage}/>
    </View>
)

并将样式定义为

var styles = StyleSheet.create({
container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     flexDirection: 'column',
},
     backgroundImage:{
     width:320,
     height:480,
   }
...

但是通过这种方式,我应该如何找到实际的iPhone屏幕尺寸?

我见过一个用于访问像素密度的API,但与屏幕尺寸无关...


答案 1

(这已被弃用,现在您可以使用ImageBackground

这就是我的做法。主要交易是摆脱静态固定尺寸。

class ReactStrap extends React.Component {
  render() {
    return (
      <Image source={require('image!background')} style={styles.container}>
        ... Your Content ...
      </Image>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    // remove width and height to override fixed static size
    width: null,
    height: null,
  }
};

答案 2

您可以在元素上使用样式,使其填充整个屏幕。然后,您可以使用其中一种图像大小调整模式使图像完全填充元素:flex: 1<Image>

<Image source={require('image!egg')} style={styles.backgroundImage} />

风格:

import React from 'react-native';

let { StyleSheet } = React;

let styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    resizeMode: 'cover', // or 'stretch'
  }
});

我很确定你可以摆脱包装你的图像,这将工作。<View>