Skip to content

Instantly share code, notes, and snippets.

@andreipfeiffer
Created April 29, 2017 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreipfeiffer/7313825903facec12ee928b68555f565 to your computer and use it in GitHub Desktop.
Save andreipfeiffer/7313825903facec12ee928b68555f565 to your computer and use it in GitHub Desktop.
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