Skip to content

Instantly share code, notes, and snippets.

@matthamil
Created August 7, 2017 19:47
Show Gist options
  • Save matthamil/b79b24d133ea4461d4f9f0bb90f72b7e to your computer and use it in GitHub Desktop.
Save matthamil/b79b24d133ea4461d4f9f0bb90f72b7e to your computer and use it in GitHub Desktop.
// @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