渲染网络图像并保持高度的纵横比

Render network images and maintain aspect ratio for height

React-native: 0.47.1

当宽度为 100% 时,如何保持高度的纵横比?基本上我想在保持纵横比的同时自动缩放高度。图片将显示在 FlatList 中(不一定,如果有其他情况我很乐意更改 FlatList)。图像显示在 state 中设置的 data 数组中:

export default class ImageTest extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data : [
        {id: 1, name: "image1", url: "http://urlOfImage.com/1.jpg"}
        {id: 2, name: "image2", url: "http://urlOfImage.com/2.jpg"}
        {id: 3, name: "image3", url: "http://urlOfImage.com/3.jpg"}
        {id: 4, name: "image4", url: "http://urlOfImage.com/4.jpg"}
        {id: 5, name: "image5", url: "http://urlOfImage.com/5.jpg"}
      ];
    }
  }

  render() {
    return (
    <View style={styles.container}>
        <FlatList
            data={this.state.data}
            renderItem = {({item})=> 
               <Text style={styles.item}>{item.name}</Text>
               <Image 
                   source={uri: item.url}
                   style={styles.myImageStyle} />
            }
        />
    </View>
    )
  }
}

const styles = StyleSheet.create(
  myImageStyle: {
    width: Dimensions.get('window').width,
    height: /* WHAT DO I PUT HERE ?? */
  }
)

所以图片的高度可能会有所不同,原始高度可能是700px,有些可能是1200px,甚至是方形图片。我如何定义每个图像的高度,因为它们来自数组?

非常感谢

您可以从 URI 获取图像的尺寸。您可以遍历数组并使用 Image 组件中包含的静态方法 getSize() 获取每个图像的尺寸。这是一个documentation for this method

示例:

const preloadedImgData = []
this.state.data.forEach((img) => {
   Image.getSize(img.url, (w, h) => {
      img.dimensions = {w, h}
      preloadedImgData.push(img)
   })
})

我不确定上面的代码是否 100% 正确,但你明白了:)

编辑:

你也可以使用这个模块,它应该为你做所有事情:react-native-fit-image

- 我不是这个模块的所有者