【问题标题】:How to use ImageBackground to set background image for screen in react-native如何使用 ImageBackground 为 react-native 中的屏幕设置背景图像
【发布时间】:2018-04-03 20:37:48
【问题描述】:

当我在 react-native 中使用时,它会警告说不推荐使用与孩子一起使用,并且将来会出错。而是用户。

所以, 如果我使用它不会给出我正在使用的预期结果

这是我为使用而编写的代码

<ImageBackground source={require('../../img/splash/splash_bg.png')} style={styles.backgroundImage} >
        </ImageBackground>

样式代码是

const styles = StyleSheet.create({
backgroundImage: {
    flex: 1,
    // width: undefined,
    // height: undefined,
    // flexDirection: 'column',
    // backgroundColor:'transparent',
    // justifyContent: 'flex-start',


},}

【问题讨论】:

  • 根据github.com/facebook/react-native/blob/…,ImageBackground 接受两种样式道具——style 和 imageStyle——(显然)分别应用于内部 View 和 Image。还值得注意的是,容器样式中的高度和重量值会自动应用于图像样式。
  • 我试过只使用 没有任何父母或孩子,但仍然无法获得预期的结果。

标签: javascript react-native imagebackground


【解决方案1】:

两个选项:

  1. 尝试将宽度和高度设置为设备屏幕的宽度和高度
  2. 好老位置绝对

#2 的代码:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}

编辑: 对于选项 #2,您可以尝试使用 resizeMode="stretch|cover"

编辑 2: 请记住,选项 #2 会按此顺序渲染图像,然后是之后的所有内容,这意味着某些像素会被渲染两次,这可能会对性能产生非常小的影响(通常不明显),但仅供您参考

【讨论】:

    【解决方案2】:

    你可以在 React Native 上使用 "ImageBackground" 组件。

    <ImageBackground
      source={yourSourceFile}
      style={{width: '100%', height: '100%'}}
    > 
        <....yourContent...>
    </ImageBackground>
    

    【讨论】:

    • 我不知道这是否奇怪,但如果我没有指定“宽度”和“高度”属性,它只会给我一个错误,而且我没有在任何地方看到这个记录.你的回答让我发现出了什么问题:D
    【解决方案3】:
    const { width, height } = Dimensions.get('window')
    
    
    <View style={{marginBottom: 20}}>
       <Image 
            style={{ height: 200, width: width, position: 'absolute', resizeMode: 'cover' }}
            source={{ uri: 'https://picsum.photos/'+width+'/200/?random' }}
                    />
       <View style={styles.productBar}>
           <View style={styles.productElement}>
                <Image
                      style={{ height: 160, width: width - 250, position: 'relative', resizeMode: 'cover' }}
                      source={{ uri: 'https://picsum.photos/'+ 250 +'/160/?random' }}
                            />
           </View>
           <View style={styles.productElement}>
                 <Text style={{ fontSize: 16, paddingLeft: 20 }}>Başlık</Text>
                 <Text style={{ fontSize: 12, paddingLeft: 20, color: "blue"}}>Alt Başlık</Text>
           </View>
       </View>
    </View>
    
    
    
     productBar: {
        margin: 20,
        marginBottom: 0,
        justifyContent: "flex-start" , 
        flexDirection: "row"
      },
      productElement: {
        marginBottom: 0, 
     },
    

    【讨论】:

      【解决方案4】:
           <ImageBackground
                  source={require("../assests/background_image.jpg")}
                  style={styles.container}
      
              >
                  <View
                      style={{
                          flex: 1,
                          justifyContent: "center",
                          alignItems: "center"
                      }}
                  >
                      <Button
                          onPress={() => this.props.showImagePickerComponent(this.props.navigation)}
                          title="START"
                          color="#841584"
                          accessibilityLabel="Increase Count"
                      />
                  </View>
              </ImageBackground>
      

      请使用此代码在 react native 中设置背景图片

      【讨论】:

      • container: { flex: 1, //justifyContent: "center", //alignItems: "center", backgroundColor: "#F5FCFF" },
      • 虽然这个答案可能是正确且有用的,但最好在其中附上一些解释来解释它如何帮助解决问题。如果有更改(可能不相关)导致它停止工作并且用户需要了解它曾经是如何工作的,这在未来变得特别有用。
      【解决方案5】:

      我通过以下方式实现了这一目标:

      import { ImageBackground } from 'react-native';
      
      <ImageBackground style={ styles.imgBackground } 
                       resizeMode='cover' 
                       source={require('./Your/Path.png')}>
      
         //place your now nested component JSX code here
      
      </ImageBackground>
      

      然后是样式:

      imgBackground: {
              width: '100%',
              height: '100%',
              flex: 1 
      },
      

      【讨论】:

      • 从 'react-native' 导入 { ImageBackground ];应该将 ] 更改为 } 对吗?
      【解决方案6】:

      我认为这会对你有所帮助..

      import React, { Component } from 'react';
      import { homePageStyles } from '../styles/Style';
      import { Text, ImageBackground } from 'react-native';
      import HomePageWallpaper from '../images/homePageWallpaper.jpg';
      
      export default class Home extends Component {
          render() {
              return (
                  <ImageBackground source={HomePageWallpaper} style={{ flex: 1, justifyContent: 'center', width: null, height: null }}>
                      <Container>                    
                          <Content>
                              <Text style={homePageStyles.description_text}>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</Text>
                          </Content>
                      </Container >
                  </ImageBackground>
              );
          }
      }
      

      【讨论】:

        【解决方案7】:

        我在背景图像及其子组件(包括徽标图像)方面遇到了同样的问题。 浪费了几个小时后,我找到了解决这个问题的正确方法。 这肯定对你有帮助。

        var {View, Text, Image, ImageBackground} = require('react-native');
        import Images from '@assets';
        
        export default class Welcome extends Component {
            render() {
                return (
                    <ImageBackground source={Images.main_bg} style={styles.container}>
                        <View style={styles.markWrap}>
                            <Image source={Images.main_logo} 
                            style={styles.mark} resizeMode="contain" />
                        </View>
                        <View style={[styles.wrapper]}>
                            {//Here put your other components}
                        </View>              
                        
                    </ImageBackground>
                );
            }
        }
        
        var styles = StyleSheet.create({
            container:{
                flex: 1,
            },
            markWrap: {
                flex: 1,
                marginTop: 83,
                borderWidth:1, borderColor: "green"
              },
            mark: {
                width: null,
                height: null,
                flex: 1,
            },
            wrapper:{
                borderWidth:1, borderColor: "green",///for debug
                flex: 1,
                position:"relative",
            },
        }
        

        Logo on background Image

        (PS:我在这个屏幕上放的是虚拟图像而不是真实的公司标志。)

        【讨论】:

          【解决方案8】:

          ImageBackground 是一个非常简单实用的组件。将您的组件作为嵌套组件放在ImageBackground 中,并使用position 调整组件的位置。

          这是一个例子。

          <ImageBackground
            source={{ uri: hoge }}
            style={{
              height: 100,
              width: 100,
              position: 'relative', 
              top: 0,
              left: 0
            }}
          >
            <Text
              style={{
                fontWeight: 'bold',
                color: 'white',
                position: 'absolute', 
                bottom: 0, 
                left: 0
              }}
            >
              Hello World
            </Text>
          </ImageBackground>

          【讨论】:

            【解决方案9】:

            这里是 RN 文档的链接:https://facebook.github.io/react-native/docs/images

            熟悉网络的开发人员提出的一个常见功能请求是背景图像。要处理这个用例,您可以使用 &lt;ImageBackground&gt; 组件,它与 &lt;Image&gt; 具有相同的属性,并添加任何您想要在其上叠加的子组件。

            在某些情况下您可能不想使用&lt;ImageBackground&gt;,因为实现非常简单。请参阅&lt;ImageBackground&gt; 的源代码了解更多信息,并在需要时创建您自己的自定义组件。

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

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

            还要注意,文件路径是相对于组件所在目录的。

            【讨论】:

            • 我像你一样设置背景图片。但是如果我在 中添加 ,我无法向下滚动超出屏幕大小。请参考我的图片imgur.com/xP0LCFL
            【解决方案10】:
            const img = '../../img/splash/splash_bg.png';
            <ImageBackground  source={{ uri: img }} style={styles.backgroundImage} >
                </ImageBackground>
            

            这对我有用。 可以在这里找到对 RN 文档的参考。我通过阅读这个来写我的 - https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

            【讨论】:

              【解决方案11】:

              添加背景图片,React Native是基于组件的,ImageBackground组件需要两个props style={{}}source={require( '')}

               <ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}> 
              <....yourContent Goes here...>
                  </ImageBackground>
              

              【讨论】:

                【解决方案12】:
                .hero-image {
                  background-image: url("photographer.jpg"); /* The image used */
                  background-color: #cccccc; /* Used if the image is unavailable */
                  height: 500px; /* You must set a specified height */
                  background-position: center; /* Center the image */
                  background-repeat: no-repeat; /* Do not repeat the image */
                  background-size: cover; /* Resize the background image to cover the entire container */
                }
                

                look result

                【讨论】:

                  【解决方案13】:

                  您必须先导入背景组件才能在您的代码中使用背景图像

                  【讨论】:

                    【解决方案14】:

                    我在 Google 上搜索如何在 2021 年实现这一目标,因此我将继续说明我是如何实现这一目标的。注意:我在我的项目中使用styled-components。另一件要提的是,您可能不需要额外的View 组件,但我在Background 组件内使用SafeAreaView 组件在iOS 的状态栏下方添加额外的间距。

                    import styled from 'styled-components';
                    
                    const Background = styled.ImageBackground`
                      flex: 1;
                      resize-mode: cover; // Not sure if this helps, but it was used in the docs, listed below
                      justify-content: center;
                    `;
                    
                    const Container = styled.SafeAreaView`
                      flex: 1;
                    `;
                    
                    ...
                    return (
                      <Background source={require('../assets/image.png')}>
                        <Container>
                          // rest of your components
                        </Container>
                      </Background>
                    )
                    ...
                    

                    docs

                    【讨论】:

                      猜你喜欢
                      • 2021-02-28
                      • 1970-01-01
                      • 2020-10-27
                      • 2015-09-19
                      • 1970-01-01
                      • 1970-01-01
                      • 2018-04-22
                      • 2020-09-17
                      • 2021-01-22
                      相关资源
                      最近更新 更多