본문 바로가기

Study/React-Native

[React-Native] 디바이스 크기에 따른 반응형 UI 구현 방법 (moderateScale, Dimensions, useWindowDimensions)

moderateScale

  • 다양한 화면 크기와 해상도에 대응하기 위해 사용되는 함수
import { Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');

// 작업 환경 Size 설정
const guidelineBaseWidth = 375; 
const guidelineBaseHeight = 667;

// 너비 기준 크기 조정 함수
const horzScale = (size: number) => (width / guidelineBaseWidth) * size;

// 높이 기준 크기 조정 함수
const vertScale = (size: number) => (height / guidelineBaseHeight) * size;

// 크기 조정 함수 (가로, 세로 스케일 조합)
const moderateScale = (size: number, factor = 0.5) =>
  size + (horzScale(size) - size) * factor;

export { horzScale, vertScale, moderateScale };

 

장점 :

  • 일관된 UI: 다양한 화면 크기에서 일관된 사용자 경험을 제공
  • 유연성: factor 매개변수를 통해 조정의 강도를 제어
  • 개발 효율성: 개발자가 각 디바이스에 대해 별도의 스타일을 작성할 필요가 없어짐

=> 디바이스 간의 UI 차이를 최소화하고, 다양한 화면 크기에 대응하는 반응형 디자인을 쉽게 구현 가능함!


Dimensions

  • get() : 창의 너비와 높이를 얻을 수 있음
static get(dim: 'window' | 'screen'): ScaledSize;
  • dim :
    • 'window' : window's Width/Height (현재 보이는 창의 크기, 동적)
    • 'screen' : device's screen Width/Height (디바이스의 물리적 크기, 고정 값)
    • 웹 브라우저의 경우 일관성을 위해 'screen'과 'window' 모두 브라우저 뷰포트 크기를 반환하도록 설계됨
  • return :
    • { width, height, scale, fontScale }
  • 사용 예시 :
import {Dimensions} from 'react-native';

// window Width/Height (현재 보이는 창의 크기, 동적)
const { width, height } = Dimensions.get('window');

// device's screen Width/Height (디바이스의 물리적 크기, 고정 값)
const { width, height } = Dimensions.get('screen');

useWindowDimensions

  • React Native 0.59 버전부터 사용 가능한 훅
  • 창 크기가 변경될 때마다 자동으로 컴포넌트를 리렌더링
    • Dimensions.get('window')를 단독으로 사용할 때는 창 크기 변경에 자동으로 반응하지 않지만
    • useWindowDimensions 훅을 사용하면 웹 환경에서도 창 크기 변경에 동적으로 대응할 수 있음
import {useWindowDimensions} from 'react-native';

function MyComponent() {
  // width와 height는 창 크기가 변경될 때마다 업데이트됨
  const { width, height } = useWindowDimensions();
}