Created
October 19, 2016 21:34
-
-
Save faceyspacey/87d6471974b90978704f40ef522b8bd3 to your computer and use it in GitHub Desktop.
RNW Image component that does not use the backgroundImage property
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 React, { Component } from 'react' | |
import { | |
View, | |
ActivityIndicator, | |
StyleSheet, | |
} from 'react-native' | |
export default class Image extends Component { | |
constructor(props, context) { | |
super(props, context) | |
this.state = { | |
width: 0, | |
height: 0 | |
} | |
} | |
onLoad(e) { | |
let {naturalWidth: imageWidth, naturalHeight: imageHeight} = e.target | |
let {width: containerWidth, height: containerHeight} = this.props | |
let imageAspect = imageWidth/imageHeight | |
let containerAspect = containerWidth/containerHeight | |
let width | |
let height | |
//replicating css property: `background-size: cover;` | |
if(containerAspect >= imageAspect) { | |
width = containerWidth | |
height = width/imageAspect | |
} else { | |
width = containerHeight*imageAspect | |
height = containerHeight | |
} | |
this.setState({width, height}) | |
} | |
render() { | |
let {source, style, animating} = this.props | |
let {width, height} = this.state | |
let coverStyle = {display: 'block', width, height} | |
let src = source && source.uri ? source.uri : source | |
let isLoading = !width | |
return ( | |
<View style={[style, styles.imageContainer]}> | |
<img | |
onLoad={this.onLoad.bind(this)} | |
src={src} | |
style={coverStyle} | |
/> | |
{isLoading && <ActivityIndicator animating={true} size={50} style={styles.activity} />} | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
imageContainer: { | |
overflow: 'hidden', | |
justifyContent: 'center', //vertically center image :) | |
alignItems: 'center', //horizontally center image :) | |
}, | |
activity: { | |
position: 'absolute', | |
top: '50%', | |
left: '50%', | |
marginLeft: -25, | |
marginTop: -25, | |
zIndex: 1, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment