Created
August 7, 2017 19:47
-
-
Save matthamil/b79b24d133ea4461d4f9f0bb90f72b7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import React from 'react'; | |
import { Image, View } from 'react-native'; | |
/** | |
* Resizes an image based on the size of its container. | |
*/ | |
export default class DynamicImage extends React.Component<void, *, *> { | |
constructor(props: *) { | |
super(props); | |
this.state = { | |
height: 0, | |
width: 0, | |
}; | |
this._onLayout = this._onLayout.bind(this); | |
} | |
_onLayout(event: Object) { | |
const containerWidth = event.nativeEvent.layout.width; | |
Image.getSize(this.props.source.uri, (width: number, height: number) => { | |
this.setState((): { width: number, height: number } => ({ | |
width: containerWidth, | |
height: containerWidth * height / width | |
})); | |
}); | |
} | |
render(): React.Element<*> { | |
return ( | |
<View | |
onLayout={this._onLayout}> | |
<Image | |
source={this.props.source} | |
style={{ | |
...this.props.style, | |
width: this.state.width, | |
height: this.state.height | |
}}/> | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment