首页指南参考教程

设置组件的背景图片

了解如何使用 ImageBackground 组件来设置组件的背景图片。


ImageBackground 组件 允许你在 Expo 和 React Native 应用中将图片显示为另一个组件的背景。例如,你可以在应用中使用屏幕容器视图中的 ImageBackground 设置屏幕的背景图片。

¥The ImageBackground component lets you display an image as the background of another component in Expo and React Native apps. For example, you can set the background image of a screen in your app with ImageBackground inside the screen's container view.

该组件在概念上类似于 CSS 的 background-image 样式表属性和 backgroundImage DOM 样式属性。

¥This component is conceptually similar to CSS's background-image stylesheet property and the backgroundImage DOM style property.

如何使用 ImageBackground

¥How to use ImageBackground

ImageBackground 组件接受的 props 与 Image 组件大致相同,但有一些区别:

¥The ImageBackground component accepts mostly the same props as the Image component with a few differences:

  • style 属性应用于封装内部图片的视图。

    ¥The style prop is applied to a view that wraps an inner image.

  • imageStyle 属性应用于图片本身。

    ¥The imageStyle prop is applied to the image itself.

  • imageRef 属性也应用于内部图片。

    ¥The imageRef prop also is applied to the inner image.

示例

¥Example

Using ImageBackground component
import { ImageBackground, StyleSheet, Text, View } from 'react-native';

const image = { uri: "https://expo.nodejs.cn/static/images/tutorial/background-image.png" };

export default function App() {
  return (
  <View style={styles.container}>
    <ImageBackground source={image} style={styles.image}>
      <Text style={styles.text}>Elements</Text>
      <Text style={styles.text}>in Front of</Text>
      <Text style={styles.text}>Background</Text>
    </ImageBackground>
  </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  image: {
    flex: 1,
    resizeMode: 'cover',
    justifyContent: 'center',
  },
  text: {
    color: 'white',
    fontSize: 42,
    fontWeight: 'bold',
    textAlign: 'center',
    backgroundColor: '#000000a0',
  },
});

上面的示例渲染的屏幕如下:

¥The example above renders a screen as following:

Expo 中文网 - 粤ICP备13048890号