forked from wassgha/react-native-fullwidth-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (53 loc) · 1.76 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
/*
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 } 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 && this.props.source.uri) {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: containerWidth,
height: containerWidth * height / width
})
})
}
}
render() {
return (
<View ref={component => this._root = component} onLayout={this._onLayout.bind(this)}>
<Image
source={this.props.source}
style={[this.props.style, {
width: this.state.width,
height: this.state.height
}]}
/>
</View>
)
}
}