【问题标题】:How can I add a background image to my react native app?如何向我的反应原生应用程序添加背景图像?
【发布时间】:2022-02-08 14:22:49
【问题描述】:

我对本机反应还很陌生,但我有一些经验。通过遵循我已经完成的教程并进行自己的修改,我正在为 ios 和 android 创建自己的应用程序。在创建应用程序的过程中,我忘记添加背景图像。经过几天的挣扎,我很绝望,所以我决定在这里问我的问题。

我正在尝试将背景图片添加到我的 App.js 文件中。图像加载正确,但我的页面内容(位于<LifelineNavigator /> 内)要么隐藏,要么在 android 中消失。而对于 ios,内容似乎在一个小的居中 flexbox 中。另外,我正在尝试删除白色背景。

任何建议肯定会有所帮助。非常感谢!上帝保佑!

这是我的代码:

import React, { useState } from "react";
import { StyleSheet, View, ImageBackground } from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
import { enableScreens } from "react-native-screens";
    
import LifelineNavigator from "./src/navigation/LifelineNavigator";

enableScreens();

const fetchFonts = () => {
   return Font.loadAsync({
      "Gotham-Medium": require("./src/assets/fonts/Gotham-Font/Gotham-Medium.otf")

const image = {
    uri: "https://i.ibb.co/8z6QbTS/Lifeline-Gradient-Background-24.png",
    };

const App = () => {
  const [fontLoaded, setFontLoaded] = useState(false);

  if (!fontLoaded) {
    return (
      <AppLoading
        startAsync={fetchFonts}
        onFinish={() => setFontLoaded(true)}
        onError={(err) => console.log(err)}
      />
    );
  }

  return (
    <View >
      <ImageBackground source={image} style={styles.image}>
        <View style={ styles.container }>
            <LifelineNavigator />
        </View>
      </ImageBackground> 
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  image: { 
    width: "100%", 
    height: "100%" ,
  }
});

export default App;

IOS Screenshot

Android Screenshot

【问题讨论】:

    标签: android ios react-native background-image imagebackground


    【解决方案1】:
    import React from "react";
    import { ImageBackground, StyleSheet, Text, View } from "react-native";
    
    const image = { uri: "https://reactjs.org/logo-og.png" };
    
    const App = () => (
      <View style={styles.container}>
        <ImageBackground source={image} resizeMode="cover" style={styles.image}>
          <Text style={styles.text}>Inside</Text>
        </ImageBackground>
      </View>
    );
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      image: {
        flex: 1,
        justifyContent: "center"
      },
      text: {
        color: "white",
        fontSize: 42,
        lineHeight: 84,
        fontWeight: "bold",
        textAlign: "center",
        backgroundColor: "#000000c0"
      }
    });
    
    export default App;
    

    关注本文档 > https://reactnative.dev/docs/imagebackground 它可能会解决您的问题

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多