2

React-native: 0.47.1

How would I maintain the aspect ratio for height when the width is 100%? Basically I want to auto scale the height while maintaining the aspect ratio. The images will be displayed in a FlatList (not necessarily, if something else worls I'm happy to change the FlatList). Images are displayed from an array of data which is set in the state:

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 ?? */
  }
)

So the images may vary in height, original height may be 700px, some maybe 1200px, or even a square image. How would I define the height for each image since they're coming from an array?

Many thanks

Somename
  • 3,376
  • 16
  • 42
  • 84

1 Answers1

3

You can take a dimensions of the image from URI. You can loop through your array and take the dimensions for each image using static method getSize() included in Image component. Here is a documentation for this method

Example:

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

I'm not sure if above code is 100% correct but you got the idea :)

EDIT:

Also you can use this module which should do everything for you: react-native-fit-image

- I'm not owner of this module

mkatanski
  • 508
  • 6
  • 19
  • It works! The `fit-image` module did the trick. I'm going to explore it and see how they made it work. It doesn't work on local images as of now but it's marvelous! Thanks a ton. I actually had a brief look at it and skipped it as the first example stated to mention the dimensions beforehand. I should've tested it. Thanks again mate. cheers!! – Somename Aug 13 '17 at 21:51
  • https://www.npmjs.com/package/react-native-fit-image works like a charm... – Seunope Jun 19 '18 at 16:58