Created
April 29, 2017 16:27
-
-
Save andreipfeiffer/7313825903facec12ee928b68555f565 to your computer and use it in GitHub Desktop.
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
import { Image, Dimensions } from 'react-native'; | |
export default class RemoteImage extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
// this data could be static or provided by a server or api | |
url: 'https://...', | |
originalWidth: 1920, | |
originalHeight: 1080, | |
// this data will be calculated and | |
// the image will be displayed based on these sizes | |
resizedWidth: 0, | |
resizedHeight: 0 | |
}; | |
}, | |
componentDidMount() { | |
Image.getSize( | |
imageUrl, | |
(originalWidth, originalHeight) => { | |
this.setImageSize(); | |
} | |
); | |
}, | |
setImageSize() { | |
// get device dimensions | |
const {width, height} = Dimensions.get('window'); | |
const resizedRatio = originalWidth / width; | |
const resizedHeight = originalHeight / resizedRatio; | |
this.setState({ | |
// the width of the displayed image is the width of the device | |
resizedWidth: width, | |
// the height of the displayed image is the calculated height | |
resizedHeight: resizedHeight | |
}); | |
}, | |
render() { | |
const {resizedWidth, resizedHeight, url} = this.state; | |
let img; | |
if (resizedWidth || resizedHeight) { | |
img = <Image | |
source={{uri: url}} | |
style={{width: resizedWidth, height: resizedHeight}} | |
/>; | |
} | |
return ( | |
{img} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment