图片缩小放大 自适应组件 react

478 阅读1分钟

实现一个可以将图片保持长宽比的组件

需要的参数: 1 图片来源地址 2 高固定,宽度自适应 3 宽度固定,高度自适应 4 style

import React, { useEffect, useState } from 'react';
import { Image, ImageStyle } from 'react-native';

interface Props {
  imgUrl: string;
  width?: number;
  height?: number;
  style?: ImageStyle;
}

const AutoRationImage = ({ imgUrl, width, height, style }: Props) => {
  const [realHeight, setRealHeight] = useState(0);
  const [realWidth, setRealWidth] = useState(0);

  useEffect(() => {
    Image.getSize(
      imgUrl,
      (imgWidth, imgHeight) => {
        if (width) {
          const ratio = imgWidth / width;
          const tmpHeight = imgHeight / ratio;
          setRealHeight(tmpHeight);
        }
        if (height) {
          const ratio = imgHeight / height;
          const tmpWidth = imgWidth / ratio;
          setRealWidth(tmpWidth);
        }
      },
      () => {
        //
      }
    );
  }, [imgUrl, width]);

  if (width) {
    return (
      <Image
        source={{ uri: imgUrl }}
         resizeMode="stretch"
        style={[
          style,
          {
            width:  width,
            height: realHeight,
          },
        ]}
      />
    );
  }

  if (height) {
    return (
      <Image
        source={{ uri: imgUrl }}
        resizeMode="stretch"
        style={[
          style,
          {
            width:realWidth,
            height: height,
          },
        ]}
      />
    );
  }

  return <></>;
};

export default AutoRationImage;