美文网首页
ReactNative 开发Image图片自适应宽高

ReactNative 开发Image图片自适应宽高

作者: 心里有了一个宝宝 | 来源:发表于2023-06-19 17:54 被阅读0次

    1. 如果是本地图片

    主要是 aspect-radio css标签用法,保持纵横比,需用看图软件查看图片宽高然后填入aspectRadio 属性,比如这里我的 sss.png 图片 1700 是宽,600 是高则填写 1700 / 600

    Example: 宽度100%,高度自适应
    <Image source={require('../../assetc/images/sss.png')} style={{width: '100%', aspectRadio: 1700 / 600}} />

    2. 如果是远程图片

    远程图片需要异步先获取一下尺寸,再动态更改 Image 的 height

    import {Image, useWindowDimensions} from 'react-native';
    
    const Example = () => {
      const [imageHeight, setImageHeight] = React.useState(0);
      const {width} = useWindowDimensions();
    
      React.useEffect(() => {
        init();
      }, []);
    
      async function init(){
        //  todo..获取远程API
        Image.getSize("https://xx.com/ddd.png", (w, h) => {
          setImageHeight(width / w * h);  // 根据屏幕宽得到图片宽缩放比例然后乘到高度上
        });
      }
      
      return <View>
       <Image source={require('../../assetc/images/sss.png')} style={{width: '100%', height: imageHeight}} />
      </View>
    }
    
    
    
    
    

    相关文章

      网友评论

          本文标题:ReactNative 开发Image图片自适应宽高

          本文链接:https://www.haomeiwen.com/subject/rameydtx.html