Skip to content

Instantly share code, notes, and snippets.

@shubhnik
Forked from mikelambert/ProportionalImage.js
Last active October 23, 2017 11:02
Show Gist options
  • Save shubhnik/afd4acfa8512d7fead1db4e7d48c1097 to your computer and use it in GitHub Desktop.
Save shubhnik/afd4acfa8512d7fead1db4e7d48c1097 to your computer and use it in GitHub Desktop.
Renders an Image that stays proportionally sized to its original dimensions. Also check this issue ----> https://github.com/facebook/react-native/issues/858
var ProportionalImage = React.createClass({
getInitialState() {
return {
style: {}
};
},
propTypes: {
originalWidth: React.PropTypes.number.isRequired,
originalHeight: React.PropTypes.number.isRequired,
},
onLayout(e) {
var layout = e.nativeEvent.layout;
var aspectRatio = this.props.originalWidth / this.props.originalHeight;
var measuredHeight = layout.width / aspectRatio;
var currentHeight = layout.height;
if (measuredHeight != currentHeight) {
this.setState({
style: {
height: measuredHeight
}
});
}
},
render() {
// We catch the onLayout in the view, find the size, then resize the child (before it is laid out?)
return (
<View
onLayout={this.onLayout}
>
<Image
{...this.props}
style={[this.props.style, this.state.style]}
/>
</View>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment