/
index.js
81 lines (72 loc) · 1.92 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
react-native-fullwidth-image
Original idea taken from
https://stackoverflow.com/questions/29642685/maintain-aspect-ratio-of-image-with-full-width-in-react-native/40207328
*/
import React, { Component } from 'react'
import { View, Image, StyleSheet } from 'react-native'
export default class FullWidthImage extends Component {
constructor(props) {
super(props)
this.state = {
width: props.width || null,
height: props.height || null
}
}
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps)
}
_onLayout(event) {
const containerWidth = event.nativeEvent.layout.width
if (this.props.ratio) {
this.setState({
width: containerWidth,
height: containerWidth * this.props.ratio
})
} else if (this.props.width && this.props.height) {
this.setState({
width: containerWidth,
height: containerWidth * (this.props.height / this.props.width)
})
} else if (this.props.source) {
let source = this.props.source
if (typeof source !== 'string') {
source = this.props.source.uri
}
Image.getSize(source, (width, height) => {
this.setState({
width: containerWidth,
height: (containerWidth * height) / width
})
})
}
}
render() {
return (
<View
ref={component => (this._root = component)}
onLayout={this._onLayout.bind(this)}
style={styles.container}
>
<Image
source={this.props.source}
style={[
this.props.style,
{
width: this.state.width,
height: this.state.height
}
]}
onLoad={this.props.onLoad}
onLoadEnd={this.props.onLoadEnd}
onLoadStart={this.props.onLoadStart}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
alignSelf: 'stretch'
}
})