react native图片自动缩放

565 阅读1分钟

我个人选择的最简单方案是,使用resizeMode属性:

<Image
    source={require('./local_path_to/your_image.png')}
    style={{ width: 30 }}
    resizeMode="contain"
 />

其它方案,本地图片

const Demo = () => {
    const scaleHeight = ({ source, desiredWidth }) => {
        const { width, height } = Image.resolveAssetSource(source)

        return desiredWidth / width * height
    }

    const imageSource = './local_image.png'
    const imageWidth = 150
    const imageHeigh = scaleHeight({
        source: require(imageSource),
        desiredWidth: imageWidth
    })
    
    return (
        <View>
            <Image
                source={require(imageSource)}
                style={{
                    width: imageWidth,
                    height: imageHeigh
                }}
            />
        </View>
    )
}

其它方案,远程图片

const RemoteImage = ({uri, desiredWidth}) => {
    const [desiredHeight, setDesiredHeight] = React.useState(0)

    Image.getSize(uri, (width, height) => {
        setDesiredHeight(desiredWidth / width * height)
    })

    return (
        <Image
            source={{uri}}
            style={{
                width: desiredWidth,
                height: desiredHeight
            }}
        />
    )
}

const Demo = () => {
    return (
        <View>
            <RemoteImage
                uri="https://via.placeholder.com/350x150"
                desiredWidth={200}
            />
        </View>
    )
}

其它方案二:

//创建一个计算图片宽高比的钩子函数

function useImageAspectRatio(imageUrl) {
  const [aspectRatio, setAspectRatio] = useState(1);

  useEffect(() => {
    if (!imageUrl) {
      return;
    }

    let isValid = true;
    Image.getSize(imageUrl, (width, height) => {
      if (isValid) {
        setAspectRatio(width / height);
      }
    });

    return () => {
      isValid = false;
    };
  }, [imageUrl]);

  return aspectRatio;
}
//只需要设置width或者height其中一个值,就能自动计算另一个

function App() {
  const aspectRatio = useImageAspectRatio(imageUrl);

  return (
    <Image 
      src={{ uri: imageUrl }}
      style={{ width: 200, aspectRatio }}
    />
  )
}