Javascript 在 React Native 中添加全屏背景图像的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29322973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:11:32  来源:igfitidea点击:

What's the best way to add a full screen background image in React Native

javascriptreact-native

提问by talpaz

I wanted to add a full-screen image to the View so I write this code

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

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

and defined the style as

并将样式定义为

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

but in this way how am I supposed to find the actual iPhone screen size?

但是这样我应该如何找到实际的 iPhone 屏幕尺寸?

I've seen an API to access the Pixel Density but nothing about the screen size...

我见过一个 API 来访问像素密度,但对屏幕尺寸一无所知......

Any idea?

任何的想法?

采纳答案by Josh

You can use flex: 1styling on an <Image>element to have it fill the whole screen. You can then use one of the Image resize modes to have the image completely fill the element:

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

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

Style:

风格:

import React from 'react-native';

let { StyleSheet } = React;

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

I'm pretty sure you can get rid of the <View>wrapping your image and this will work.

我很确定你可以摆脱<View>包装你的形象,这会奏效。

回答by oronbz

(This has been deprecated now you can use ImageBackground)

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

This is how I've done it. The main deal was getting rid of the static fixed sizes.

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

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,
  }
};

回答by Vinod Sobale

Note: This solution is old. Please refer tohttps://facebook.github.io/react-native/docs/images.html#background-image-via-nestinginstead

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

Try this solution. It is officially supported. I have just tested it and works flawlessly.

试试这个解决方案。它是官方支持的。我刚刚测试过它并且工作完美。

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

And as for using it as Background image, just do the following.

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

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

回答by Tab

I tried several of these answers to no avail for android using react-native version = 0.19.0.

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

For some reason, the resizeMode inside my stylesheet did not work appropriately? However, when sytlesheet had

出于某种原因,我的样式表中的 resizeMode 无法正常工作?然而,当样式表有

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

and, within the Image tag I specified the resizeMode:

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

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

It worked perfectly! As mentioned above, you can use Image.resizeMode.cover or contain as well.

它工作得很好!如上所述,您可以使用 Image.resizeMode.cover 或 contains 。

Hope this helps!

希望这可以帮助!

回答by Hitesh Sahu

Update March 2018 Using Image is deprecated use ImageBackground

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 >

回答by Ryan Wu

Based on Braden Rockwell Napier's answer, I made this BackgroundImagecomponent

根据Braden Rockwell Napier回答,我制作了这个BackgroundImage组件

BackgroundImage.js

背景图片.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

someWhereInMyApp.js

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

回答by antoine129

If you want to use it as a background image, you will need to use the new <ImageBackground>component introduced at the end of June 2017in v0.46. It supports nesting while <Image>soon won't.

如果要将其用作背景图片,则需要使用20176 月底在 v0.46 中引入的新<ImageBackground>组件。它支持嵌套,但很快就不会了。<Image>

Here is the commitsummary:

这是提交摘要:

We are removing support of nesting views inside component. We decided to do this because having this feature makes supporting intrinsinc content sizeof the <Image>impossible; so when the transition process is complete, there will be no need to specify image size explicitly, it can be inferred from actual image bitmap.

And this is the step #0.

is very simple drop-in replacement which implements this functionality via very simple styling. Please, use instead of if you want to put something inside.

我们正在取消对组件内部嵌套视图的支持。我们决定这样做,因为具有这种特征使得配套 intrinsinc content size的的<Image>不可能的; 所以当过渡过程完成时,不需要明确指定图像大小,它可以从实际图像位图推断出来。

这是步骤#0。

是非常简单的插入式替换,它通过非常简单的样式实现了这个功能。如果您想在里面放东西,请使用代替。

回答by Pawel Sas

UPDATE to ImageBackground

更新到 ImageBackground

Since using <Image />as a container is deprecated for a while, all answers actually miss something important. For proper use choose <ImageBackground />with styleandimageStyleprop. Apply all Image relevant styles to imageStyle.

由于<Image />用作容器已被弃用一段时间,因此所有答案实际上都遗漏了一些重要内容。为了正确使用,请选择<ImageBackground />withstyleimageStyleprop。将所有与图像相关的样式应用于imageStyle.

For example:

例如:

<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

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

回答by Ali Esfandiari

Oh God Finally I find a great way for React-Native V 0.52-RC and native-base:

Oh God 最后我找到了 React-Native V 0.52-RC 和 native-base 的好方法:

Your Content Tag Should be something like this: //==============================================================

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

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

And Your essential style is : //==============================================================

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

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

It works fine friends ... have fun

它运作良好的朋友......玩得开心

回答by Braden Rockwell Napier

Since 0.14 this method won't work, so I built a static component that will make this simple for you guys. You can just paste this in or reference it as a component.

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

This should be re-useable and it will allow you to add additional styles and properties as-if it were a standard <Image />component

这应该是可重复使用的,它允许您添加其他样式和属性,就像它是标准<Image />组件一样

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

just paste this in and then you can use it like image and it should fit the entire size of the view it is in (so if it's the top view it will fill your screen.

只需粘贴它,然后你就可以像图像一样使用它,它应该适合它所在视图的整个尺寸(所以如果它是顶视图,它将填满你的屏幕。

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

Click here for a Preview Image

单击此处查看预览图像