► React Native/개발일기
[React Native] 이미지 비율 유지하면서, 사이즈 조절하는 방법
다람트리
2025. 6. 2. 21:39
반응형
이슈사항
웹 react와 다르게 react-native에서는 알아서 이미지 비율에 맞게 화면에 구현이되지 않는다.
따라서 이미지크기를 알아내고, 약간의 산술을 통해 비율을 구하여, 이미지사이즈를 조절해주어야한다.
해결방법
1. 이미지의 크기를 알아낸다. Image.getSize() 메소드를 활용하면 된다.
import { Image } from 'react-native';
Image.getSize(이미지경로, (w, h) => {
//w, h => w는 이미지의 width / h는 이미지의 height를 알아낸다
...
});
2. 화면너비와 이미지너비의 비율을 산술하여, 화면사이즈에 맞게 조정하면된다. Dimensions.get('window') 메소드를 활용하면 된다
import { Dimensions } from 'react-native';
const screenWidth = Dimensions.get('window').width; //화면 너비 사이즈
const widthScale = screenWidth/이미지너비; //이미지너비와 화면너비 간의 비율
//아래와같이, 이미지의 너비와 높이에 동일한 비율은 넣어주면, 이미지 비율이 무너지지 않는 형태로 화면에 꽉찬 이미지를 구현할 수 있다.
const fullWidthImgWidth = widthScale * 이미지너비
const fullWidthImgHeight = widthScale * 이미지높이
return(
<Image
source={{ uri: Image_URL }}
resizeMode="contain"
style={{ width: fullWidthImgWidth, height: fullWidthImgHeight }}
/>
)
공통함수 구축
공통함수로 만들어 놓으면 이미지 작업할때 활용하기 좋다
import { Dimensions, PixelRatio } from 'react-native';
// ▼ [ 화면너비, 화면높이 구하기 ]
let screenWidth = Dimensions.get('window').width;
let screenHeight = Dimensions.get('window').height;
// ▼ [ 이미지와 화면 간의 비율 구하기 ]
/**
* @param {*} imgWidth 이미지너비
* @returns 이미지너비와 화면너비 간의 비율
*/
const widthScale = imgWidth => screenWidth / imgWidth;
/**
* @param {*} imgheight 이미지높이
* @returns 이미지높이와 화면높이 간의 비율
*/
const heightScale = imgheight => screenHeight / imgheight;
// ▼ [ 희망하는 비율로 이미지 사이즈 조정하기 ]
/**
* @param {*} imgWidth 이미지너비
* @param {*} scale 비율
* @returns 이미지너비에서 희망하는 비율로 사이즈조정
*/
const fullWidthImgWidth = (imgWidth, scale) => scale * imgWidth;
/**
* @param {*} imgHeight 이미지높이
* @param {*} scale 비율
* @returns 이미지높이에서 희망하는 비율로 사이즈조정
*/
const fullWidthImgHeight = (imgHeight, scale) => scale * imgHeight;
export {
screenWidth,
screenHeight,
widthScale,
heightScale,
fullWidthImgWidth,
fullWidthImgHeight,
};
반응형