-
-
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
This file contains 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
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