Notice
Recent Posts
Recent Comments
05-04 15:47
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

YESHTML5

useImage 이미지 불러올때 Resize적용가능하게 본문

React,React-Native

useImage 이미지 불러올때 Resize적용가능하게

슬/도/아/밤/ 2022. 5. 24. 17:19
반응형

 

ReactNative에서 Image를 할때 불러들이는 이미지 크기가 다양하다. 

이미지의 가로형, 세로형에 맞춰서 컨트롤이 필요한데, resizeMode가 있긴하지만, hook로 이미지의 크기에 맞게 보여주고자한다.

코드는 아래와 같다.

사용하면서 더 추가기능이 필요하겠지만, 우선 당장 개발중인 "unsplash' 이미지 갤러이에는 적용될수 있을거 같다.

 

 

/**
 * @name useImage
 * @description
 */
import React, {useEffect, useState} from 'react'
import {StyleSheet, StyleProp, View, Image, ViewStyle, Dimensions} from 'react-native'
// *-------------------------------------------------------------------*

type Props = {
  containerStyle?: StyleProp<ViewStyle>
  url: string
  resize?: 'cover' | 'contain' | 'stretch' | 'repeat' | 'center'
  maxWidth?: number | undefined
  maxHeight?: number | undefined
}

export const useImage = ({resize, containerStyle, url, maxWidth, maxHeight}: Props) => {
  // hooks
  const _maxWidth: number = Dimensions.get('window').width - 40
  const _maxHeight: number = 400
  const [width, setWidth] = useState<number>(0)
  const [height, setHeight] = useState<number>(0)
  // *-------------------------------------------------------------------*
  /**
   * @function 이미지사이즈
   */
  const getImagSize = () => {
    Image.getSize(
      url,
      (_width, _height) => {
        setWidth(_width)
        setHeight(_height)
      },
      errorMsg => {
        console.log(errorMsg)
      },
    )
  }
  // *----- 액션시트컨텐츠
  const image = () => {
    if (!url || width === 0 || height === 0) return null
    // 조건설정
    let _width = width
    let _height = height
    if (maxWidth) {
      // *------------------- 최대width설정
      _width = maxWidth
      _height = (maxWidth * width) / height
    } else if (maxHeight) {
      // *------------------- 최대height설정
      _width = (maxHeight * height) / width
      _height = maxHeight
    } else {
      // *------------------- AutoSize설정
      if (width >= height) {
        _width = width >= _maxWidth ? _maxWidth : width
        _height = height
      } else {
        _width = width >= _maxWidth ? _maxWidth : width
        _height = height >= _maxHeight ? _maxHeight : height
      }
    }
    return (
      <View style={[styles.container, containerStyle]}>
        <Image resizeMode={resize} source={{uri: url}} style={[styles.image, {width: _width, height: _height}]} />
      </View>
    )
  }
  // useEffect
  useEffect(() => {
    getImagSize()
  }, [])
  // *-------------------------------------------------------------------
  return {width, height, image}
}
const styles = StyleSheet.create({
  /**@view */
  container: {borderWidth: 0, alignSelf: 'center'},
  /**@image */
  image: {alignSelf: 'center'},
})
/********************************************************
[사용법]

// const
const imageURL = 'https://reactnative-examples.com/wp-content/uploads/2022/02/earth.jpg'
// hooks
const {width, height, image} = useImage({url: imageURL , maxWidth:300})

<View style={{}}>{image()}</View>

*********************************************************/
반응형
Comments