Skip to content

Instantly share code, notes, and snippets.

@faceyspacey
Created October 19, 2016 21:34
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 faceyspacey/87d6471974b90978704f40ef522b8bd3 to your computer and use it in GitHub Desktop.
Save faceyspacey/87d6471974b90978704f40ef522b8bd3 to your computer and use it in GitHub Desktop.
RNW Image component that does not use the backgroundImage property
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