How to hide Status Bar without change position of app screen

52 Views Asked by At

I use react native to develop my app. I want to show Image full screen but my code let Screen of my app change position when status bar hidden.

const myApp = () => {
  const [hiddenStatusBar, setHiddenStatusBar] = useState()
  const onClickImage = useCallback(() => {
    if (hiddenStatusBar) {
        setHiddenStatusBar(false)
    } else {
        setHiddenStatusBar(true)
    }
   }, [hiddenStatusBar])
  return(
    <View style={{ flex: 1 }}>
      <Pressable onPress={onClickImage}>
        <Image source={{ uri: item?.uri }}
          style={{ width: mobileWidth, height: mobileHeight }}
          contentFit="cover"
        />
      </Pressable>
      <StatusBar hidden={hiddenStatusBar} animated={true} />
    </View>
   )
  }

What i want:

enter image description here

But my code output:

enter image description here

Can someone help me, thank you!

1

There are 1 best solutions below

1
Shailesh Yadav On

StatusBarManager.HEIGHT will return the fixed height of the status bar.

  1. top: hiddenStatusBar ? 0 : -StatusBarManager.HEIGHT
    When the status bar is visible, the ImageBackground is shifted to the top by an offset equal to the status bar height. This maintains the image ratio to be the same both before and after.
  2. StatusBar shouldn't be wrapped as a child component; instead, it should be moved to the top of the code.

With these two fixes, the resizing flicker issue gets hidden, as the image ratio is maintained in both the states.

import {
      StyleSheet,
      Pressable,
      View,
      StatusBar,
      useWindowDimensions,
      ImageBackground,
      NativeModules,
    } from 'react-native';
    import { useCallback, useState } from 'react';
    
    const { StatusBarManager } = NativeModules;
    
    export default function App() {
      const { width, height } = useWindowDimensions();
      const [hiddenStatusBar, setHiddenStatusBar] = useState();
    
      const onClickImage = useCallback(() => {
        if (hiddenStatusBar) {
          setHiddenStatusBar(false);
        } else {
          setHiddenStatusBar(true);
        }
      }, [hiddenStatusBar]);
    
      return (
        <>
          <StatusBar hidden={hiddenStatusBar} animated={true} />
          <ImageBackground
            style={{
              position: 'absolute',
              top: hiddenStatusBar ? 0 : -StatusBarManager.HEIGHT,
              width,
              height,
            }}
            resizeMode="cover"
            source={{ uri: 'https://picsum.photos/seed/picsum/200/300' }}>
            <View style={{ flex: 1 }}>
              <Pressable
                style={{
                  flex: 1,
                  opacity: 0,
                }}
                onPress={onClickImage}
              />
            </View>
          </ImageBackground>
        </>
      );
    }