【问题标题】:What's the best way to add a full screen background image添加全屏背景图像的最佳方法是什么
【发布时间】:2015-06-02 02:19:30
【问题描述】:

我想在视图中添加全屏图像,所以我编写了这段代码

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,但对屏幕尺寸一无所知...

【问题讨论】:

  • 性能如何?使用.png.jpg 可以吗?可以将壁纸图像存储在应用程序目录树中吗?还是使用其他东西更好? .svg 还是什么?

标签: javascript react-native


【解决方案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,
  }
};

【讨论】:

  • 是的,这就是 docs facebook.github.io/react-native/docs/… 应该这样做的
  • 这是最佳答案!
  • 谢谢!确保Image 是您返回的第一个组件,即容器。起初,我不小心将Image 嵌套在作为容器的View 中。
  • YellowBox.js:76 不推荐将 与孩子一起使用,并且在不久的将来会出现错误。请重新考虑布局或改用 。当我将内容添加到 时,会出现此警告。这真的很烦人。
  • 这实际上已被弃用。使用 ImageBackground 或(最佳)位置:绝对
【解决方案2】:

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

<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'
  }
});

我很确定您可以摆脱包装图像的&lt;View&gt;,这将起作用。

【讨论】:

  • 是的,它有效,我已将 Image 元素移到最顶部并将其样式设置为 backgroundImage:{ justifyContent: 'center', alignItems: 'center', flex: 1, resizeMode: Image.resizeMode.contain, }, 谢谢
  • 经过一段时间的努力后,我发现将Image 组件包装在绝对定位的View 中以使背景图像出现在屏幕上其他内容的后面是最简单的方法。
  • 重要编辑:&lt;Image src=...&gt; 现在是 &lt;Image source=...&gt;
  • 现在支持 z-index,你会改变这个答案吗?
  • 没问题,但是图像正在拉伸,并且在屏幕中启用了滚动
【解决方案3】:

注意:此解决方案已过时。请参考 https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting 代替

试试这个解决方案。它是官方支持的。我刚刚对其进行了测试,并且可以完美运行。

var styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
  }
});

至于将其用作背景图片,只需执行以下操作即可。

<Image style={styles.backgroundImage}>
  <View>
    <Text>All your stuff</Text>
  </View>
</Image>

【讨论】:

  • 什么,官方支持吗?
  • 这里alignSelfwidth有什么用?
  • 您正在将 拉伸到可用宽度,并且宽度需要为 null 才能使“拉伸”起作用
  • 仅供参考,图像组件在最新版本的 React (0.51.0) 中不能有子组件。这不再有效。
【解决方案4】:

2018 年 3 月更新使用 Image 已弃用使用 ImageBackground

  <ImageBackground 
          source={{uri: 'https://images.pexels.com/photos/89432/pexels-photo-89432.jpeg?h=350&dpr=2&auto=compress&cs=tinysrgb'}}
          style={{ flex: 1,
            width: null,
            height: null,
            }}
        >
       <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Your Contents</Text>
       </View>

 </ImageBackground >

【讨论】:

  • 这是正确的,现在您必须使用 ImageBackground,不推荐使用 Image 作为容器。此处不需要作为容器查看,您可以只使用 ImageBackground 作为主容器。
【解决方案5】:

我使用 react-native version = 0.19.0 尝试了其中几个答案,但对 android 无济于事。

由于某种原因,我的样式表中的 resizeMode 不能正常工作?但是,当 sytlesheet 有

backgroundImage: {
flex: 1,
width: null,
height: null,
}

并且,在 Image 标记中我指定了 resizeMode:

<Image source={require('path/to/image.png')} style= {styles.backgroundImage} resizeMode={Image.resizeMode.sretch}>

效果很好!如上所述,您可以使用 Image.resizeMode.cover 或包含。

希望这会有所帮助!

【讨论】:

    【解决方案6】:

    更新到 ImageBackground

    由于使用&lt;Image /&gt; 作为容器已被弃用一段时间,所有答案实际上都遗漏了一些重要的东西。为了正确使用,请选择 &lt;ImageBackground /&gt;style imageStyle prop。将所有与图片相关的样式应用到imageStyle

    例如:

    <ImageBackground
        source={yourImage}
        style={{
          backgroundColor: '#fc0',
          width: '100%', // applied to Image
          height: '100%' 
        }}
        imageStyle={{
          resizeMode: 'contain' // works only here!
        }}
    >
        <Text>Some Content</Text>
    </ImageBackground>
    

    https://github.com/facebook/react-native/blob/master/Libraries/Image/ImageBackground.js

    【讨论】:

      【解决方案7】:

      基于Braden Rockwell Napieranswer,我做了这个BackgroundImage组件

      BackgroundImage.js

      import React, { Component } from 'react'
      import { Image } from 'react-native'
      
      class BackgroundImage extends Component {
        render() {
          const {source, children, style, ...props} = this.props
          return (
            <Image source={ source }
                   style={ { flex: 1, width: null, height: null, ...style } }
                   {...props}>
              { children }
            </Image>
          )
        }
      }
      BackgroundImage.propTypes = {
        source: React.PropTypes.object,
        children: React.PropTypes.object,
        style: React.PropTypes.object
      }
      export default BackgroundImage
      

      someWhereInMyApp.js

       import BackgroundImage from './backgroundImage'
       ....
       <BackgroundImage source={ { uri: "https://facebook.github.io/react-native/img/header_logo.png" } }>
          <Text>Test</Text>
       </BackgroundImage>
      

      【讨论】:

        【解决方案8】:

        如果要将其用作背景图片,则需要使用 v0.46 中新的&lt;ImageBackground&gt; 组件introduced at the end of June 2017。它支持嵌套,而&lt;Image&gt; 很快就不支持了。

        这是commit的摘要:

        我们正在移除对组件内嵌套视图的支持。我们决定这样做是因为拥有此功能可以支持 intrinsinc content size 中的&lt;Image&gt; 不可能;所以当 过渡过程完成,将无需指定图像 显式大小,可以从实际的图像位图推断出来。

        这是第 0 步。

        是非常简单的插入式替换,它实现 通过非常简单的样式实现此功能。请用 而不是如果你想放东西 里面。

        【讨论】:

          【解决方案9】:

          天哪,我终于找到了 React-Native V 0.52-RC 和 native-base 的好方法:

          您的内容标签应该是这样的: //================================================= ===============

          <Content contentContainerStyle={styles.container}>
              <ImageBackground
                  source={require('./../assets/img/back.jpg')}
                  style={styles.backgroundImage}>
                  <Text>
                      Some text here ...
                  </Text>
              </ImageBackground>
          </Content>
          

          你的基本风格是: //================================================= ===============

          container: {
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center'
          },
          backgroundImage:{
              flex : 1,
              width : '100%'
          }
          

          效果很好的朋友……玩得开心

          【讨论】:

          • 嗨,只是想确定 ImageBackground 是从哪里导入的?
          • 好的,所以我从 react-native 导入了 ImageBackground,但是我不能设置为:100%
          • 您是否遇到过它在 Android Emulator 上显示但在设备上不显示的问题?
          • 对不起,我的回答迟了,你可以从 React Native 导入 ImageBackground: import {ImageBackground} from 'react-native';你测试过女巫装置吗?我在设备上没有发现任何问题。
          • 我的模拟器是 Nexus 5 规格。我的机器人是 Wileyfox Swift。主要区别在于分辨率,所以我在图像上检查了它,似乎图像分辨率高于你的设备,它没有显示。我尝试使用样式使图像更小,但没有奏效,因此我将图像的分辨率更改为更低,现在它似乎可以正常工作。分辨率较低并不是真正的问题,因为它是一个登录屏幕,上面有一些文本输入和按钮。非常感谢。
          【解决方案10】:
          import { ImageBackground } from "react-native";
          <ImageBackground
               style={{width: '100%', height: '100%'}}
               source={require('../assets/backgroundLogin.jpg ')}> //path here inside
              <Text>React</Text>
          </ImageBackground>
          

          【讨论】:

            【解决方案11】:

            对我来说这很好用,我使用 ImageBackground 来设置背景图片:

            import React from 'react';
            import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Image, ImageBackground } from 'react-native';
            const App: () => React$Node = () => {
            return (
                <>
                  <StatusBar barStyle="dark-content" />
                  <View style={styles.container}> 
                  <ImageBackground source={require('./Assets.xcassets/AppBackGround.imageset/2x.png')} style={styles.backgroundImage}>
                    <View style={styles.sectionContainer}>
                          <Text style={styles.title}>Marketing at the speed of today</Text>
                    </View>
                  </ImageBackground>
                  </View>
                </>
              );
            };
            
            
            const styles = StyleSheet.create({
              container: {
                flex: 1,
                fontFamily: "-apple-system, BlinkMacSystemFont Segoe UI",
                justifyContent: "center",
                alignItems: "center",
              },
              backgroundImage: {
                flex: 1,
                resizeMode: 'cover',
                height: '100%',
                width: '100%'
              },
              title:{
                color: "#9A9A9A",
                fontSize: 24,
                justifyContent: "center",
                alignItems: "center",
              },
            sectionContainer: {
                marginTop: 32,
                paddingHorizontal: 24,
              },
            });
            
            export default App;
            

            【讨论】:

              【解决方案12】:

              从 0.14 开始,这个方法不起作用,所以我构建了一个静态组件,这将使你们变得简单。您可以将其粘贴或将其作为组件引用。

              这应该是可重复使用的,它将允许您添加额外的样式和属性,就好像它是一个标准的 &lt;Image /&gt; 组件

              const BackgroundImage = ({ source, children, style, ...props }) => {
                return (
                    <Image
                      source={source}
                      style={{flex: 1, width: null, height: null, ...style}}
                      {...props}>
                      {children}
                    </Image>
                );
              }
              

              只需将其粘贴进去,然后您就可以像使用图像一样使用它,它应该适合它所在视图的整个大小(因此,如果它是顶视图,它将填满您的屏幕。

              <BackgroundImage source={require('../../assets/backgrounds/palms.jpg')}>
                  <Scene styles={styles} {...store} />
              </BackgroundImage>
              

              Click here for a Preview Image

              【讨论】:

                【解决方案13】:

                截至 2017 年 10 月的最新数据 (RN >= .46)

                import React from 'react';
                import { 
                  ...
                  ImageBackground,
                } from 'react-native';
                
                render() {
                  return (
                    <ImageBackground source={require('path/to/img')} style={styles.urStyle}>
                    </ImageBackground>
                  );
                }
                

                http://facebook.github.io/react-native/releases/0.49/docs/images.html#background-image-via-nesting

                【讨论】:

                  【解决方案14】:

                  要处理此用例,您可以使用 &lt;ImageBackground&gt; 组件,它与 &lt;Image&gt; 具有相同的属性,并添加您想要在其上叠加的任何子组件。

                  例子:

                  return (
                    <ImageBackground source={...} style={{width: '100%', height: '100%'}}>
                      <Text>Inside</Text>
                    </ImageBackground>
                  );
                  

                  更多:ImageBackground | React Native

                  请注意,您必须指定一些宽度和高度样式属性。

                  【讨论】:

                    【解决方案15】:

                    您需要确保您的图片具有 resizeMode={Image.resizeMode.contain} 或 {Image.resizeMode.stretch} 并将图片样式宽度设置为 null

                    <Image source={CharacterImage} style={{width: null,}} resizeMode={Image.resizeMode.contain}/>
                    

                    【讨论】:

                      【解决方案16】:

                      值为null的宽度和高度对我不起作用,然后我想使用顶部,底部,左侧和右侧位置并且它起作用了。 示例:

                      bg: {
                              position: 'absolute',
                              top: 0,
                              bottom: 0,
                              left: 0,
                              right: 0,
                              resizeMode: 'stretch',
                      },
                      

                      还有 JSX:

                      <Image style={styles.bg} source={{uri: 'IMAGE URI'}} />
                      

                      【讨论】:

                        【解决方案17】:

                        (RN >= .46)

                        如果你想在图像上渲染内容,组件不能包含子元素,请考虑使用绝对定位。

                        或者你可以使用 ImageBackground

                        import React from 'react';
                        import { 
                          ...
                          StyleSheet,
                          ImageBackground,
                        } from 'react-native';
                        
                        render() {
                          return (
                            
                          <ImageBackground source={require('path/to/img')} style={styles.backgroundImage} >
                              <View style={{flex: 1, backgroundColor: 'transparent'}} />
                              <View style={{flex: 3,backgroundColor: 'transparent'}} >
                          </ImageBackground>
                            
                          );
                        }
                        
                        const styles = StyleSheet.create({
                          backgroundImage: {
                                flex: 1,
                                width: null,
                                height: null,
                                resizeMode: 'cover'
                            },
                        });

                        【讨论】:

                          【解决方案18】:

                          实现背景的最简单方法:

                          <ImageBackground style={styles.container} source={require('../../images/screen_login.jpg')}>
                            <View style={styles.logoContainer}>
                              <Image style={styles.logo}
                                source={require('../../images/logo.png')}
                              />
                            </View> 
                            <View style={styles.containerTextInput}>
                              < LoginForm />
                            </View>   
                          </ImageBackground>
                          
                          const styles = StyleSheet.create({
                            container: {
                              flex: 1,
                              //   backgroundColor:"#0984e3"
                            },
                            containerTextInput: {
                              marginTop: 10,
                              justifyContent: 'center'
                            },
                          
                            logoContainer: {
                              marginTop: 100,
                              justifyContent: 'center',
                              alignItems: 'center'
                            },
                            logo: {
                              height: 150,
                              width: 150
                            }
                          });
                          

                          【讨论】:

                            【解决方案19】:

                            如果你想添加背景图片,你可以使用,但首先你必须从 'react-native' 导入它,如下所示:

                            import {ImageBackground} from 'react-native';
                            

                            然后:

                                export default function App() {
                                
                                return (
                                    <View style={styles.body}>
                            
                                        <ImageBackground source={require('./path/to/yourimage')} style={styles.backgroungImage}>
                                            <View style={styles.container}>Hello world!
                                            </View>
                                        </ImageBackground>
                                    </View>
                                );
                            }
                            
                                const styles = StyleSheet.create({
                                backgroungImage: {
                                flex: 1,
                                maxWidth: '100%',
                              }
                            });
                            

                            【讨论】:

                              【解决方案20】:

                              import React from 'react';
                              import { 
                                ...
                                StyleSheet,
                                ImageBackground,
                              } from 'react-native';
                              
                              render() {
                                return (
                                  
                                <ImageBackground source={require('path/to/img')} style={styles.backgroundImage} >
                                    <View style={{flex: 1, backgroundColor: 'transparent'}} />
                                    <View style={{flex: 3,backgroundColor: 'transparent'}} >
                                </ImageBackground>
                                  
                                );
                              }
                              
                              const styles = StyleSheet.create({
                                backgroundImage: {
                                      flex: 1,
                                      width: null,
                                      height: null,
                                      resizeMode: 'cover'
                                  },
                              });

                              【讨论】:

                              • 也许你想添加一些解释?
                              【解决方案21】:

                              如果你还没有解决,React Native v.0.42.0 有 resizeMode

                              <Image style={{resizeMode: 'contain'}} source={require('..img.png')} />
                              

                              【讨论】:

                                【解决方案22】:
                                import React, { Component } from 'react';
                                import { Image, StyleSheet } from 'react-native';
                                
                                export default class App extends Component {
                                  render() {
                                    return (
                                      <Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
                                    );
                                  }
                                }
                                
                                const s = StyleSheet.create({
                                  backgroundImage: {
                                      flex: 1,
                                      width: null,
                                      height: null,
                                  }
                                });
                                

                                你可以试试:https://sketch.expo.io/B1EAShDie(来自:github.com/Dorian/sketch-reactive-native-apps

                                文档:https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

                                【讨论】:

                                  【解决方案23】:

                                  您还可以将图像用作容器:

                                  render() {
                                      return (
                                          <Image
                                              source={require('./images/background.png')}
                                              style={styles.container}>
                                              <Text>
                                                This text will be on top of the image
                                              </Text>
                                          </Image>
                                      );
                                  }
                                  
                                  
                                  const styles = StyleSheet.create({
                                      container: {
                                          flex: 1,
                                          width: undefined,
                                          height: undefined,
                                          justifyContent: 'center',
                                          alignItems: 'center',
                                        },
                                  });
                                  

                                  【讨论】:

                                    【解决方案24】:

                                    我听说必须使用 BackgroundImage,因为将来您应该无法嵌套 Image 标签。但我无法让 BackgroudImage 正确显示我的背景。我所做的是将我的图像嵌套在 View 标记中,并设置外部 View 和图像的样式。键将宽度设置为空,并将 resizeMode 设置为“拉伸”。以下是我的代码:

                                    import React, {Component} from 'react';
                                    import { View, Text, StyleSheet, Image} from 'react-native';
                                    
                                    export default class BasicImage extends Component {
                                    	constructor(props) {
                                    	  super(props);
                                    
                                    	  this.state = {};
                                    	}
                                    
                                    	render() {
                                    		return (
                                    			<View style={styles.container}>
                                    	      <Image 
                                    	        source={this.props.source}
                                    	        style={styles.backgroundImage}
                                    	      />
                                          </View>
                                    		)
                                    	}
                                    }
                                    
                                    const styles = StyleSheet.create({   
                                    		container: {
                                    			flex: 1,
                                    			width: null,
                                    			height: null,
                                    			marginBottom: 50
                                    		},
                                        text: {
                                        		marginLeft: 5,
                                        		marginTop: 22,
                                        		fontFamily: 'fontawesome',
                                            color: 'black',
                                            fontSize: 25,
                                            backgroundColor: 'rgba(0,0,0,0)',
                                        },
                                    		backgroundImage: {
                                    			flex: 1,
                                    			width: null,
                                    			height: null,
                                    			resizeMode: 'stretch',
                                    		}
                                    });

                                    【讨论】:

                                      【解决方案25】:

                                      antoine129 所述,使用&lt;ImageBackground&gt;。现在不推荐将&lt;Image&gt; 与孩子一起使用。

                                      class AwesomeClass extends React.Component {
                                        render() {
                                          return (
                                            <ImageBackground source={require('image!background')} style={styles.container}>
                                              <YourAwesomeComponent/>
                                            </ImageBackground>
                                          );
                                        }
                                      }
                                      
                                      var styles = StyleSheet.create({
                                        container: {
                                          flex: 1,
                                        }
                                      };
                                      

                                      【讨论】:

                                        【解决方案26】:

                                        另一个简单的解决方案:

                                        <Image source={require('../assets/background.png')}
                                              style={{position: 'absolute', zIndex: -1}}/>
                                        
                                        <View style={{flex: 1, position: 'absolute'}}>
                                        
                                          {/*rest of your content*/}
                                        </View>
                                        

                                        【讨论】:

                                          【解决方案27】:

                                          我使用此代码解决了我的背景图片问题。

                                          import React from 'react';
                                          import { StyleSheet, Text, View,Alert,ImageBackground } from 'react-native';
                                          
                                          import { TextInput,Button,IconButton,Colors,Avatar } from 'react-native-paper';
                                          
                                          class SignInScreen extends React.Component {
                                          
                                              state = {
                                                 UsernameOrEmail  : '',
                                                 Password : '',
                                               }
                                              render() {
                                                return (
                                                       <ImageBackground  source={require('../assets/icons/background3.jpg')} style {styles.backgroundImage}>
                                                        <Text>React Native App</Text>
                                                      </ImageBackground>
                                                    );
                                              }
                                            }
                                          
                                          
                                              export default SignInScreen;
                                          
                                              const styles = StyleSheet.create({
                                               backgroundImage: {
                                                flex: 1,
                                                resizeMode: 'cover', // or 'stretch'
                                               }
                                             });
                                          

                                          【讨论】:

                                            【解决方案28】:

                                            ImageBackground 可能有限制

                                            其实你可以直接使用,也没有弃用。

                                            如果您想在 React Native 中添加背景图片,并且还想在该背景图片上添加其他元素,请按照以下步骤操作:

                                            1. 创建容器视图
                                            2. 创建一个宽度和高度为 100% 的图像元素。还有 resizeMode: 'Cover'
                                            3. 在 Image 元素下创建另一个 View 元素,位置为:'absolute'

                                            这是我使用的代码:

                                            import React, { Component } from 'react';
                                            import {Text, View, Image} from 'react-native';
                                            import Screen from '../library/ScreenSize'
                                            
                                            export default class MenuScreen extends Component {
                                                static navigationOptions = {
                                                  header: null
                                                }
                                                render() {
                                                    return (
                                                      <View style={{ flex: 1 }}>
                                                        <Image
                                                          style={{
                                                            resizeMode: "cover",
                                                            width: "100%",
                                                            height: "100%",
                                                            justifyContent: "center",
                                                            alignItems: "center",
                                                            opacity: 0.4
                                                          }}
                                                          source={require("../assets/images/menuBackgroundImage.jpg")}
                                                        ></Image>
                                            
                                                        <View style={{
                                                            width: Screen.width,
                                                            height: Screen.height * 0.55,
                                                            position: 'absolute',
                                                            bottom: 0}}>
                                                            <Text style={{
                                                                fontSize: 48
                                                            }}>Glad to Meet You!</Text>
                                                        </View>
                                                      </View>
                                                    );
                                                }
                                            }
                                            
                                            

                                            享受编码......

                                            输出:

                                            【讨论】:

                                              猜你喜欢
                                              • 2015-05-13
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 2015-08-17
                                              • 2016-12-31
                                              • 2016-12-24
                                              相关资源
                                              最近更新 更多