-
Notifications
You must be signed in to change notification settings - Fork 465
/
AutoSizedImage.js
53 lines (47 loc) · 1.36 KB
/
AutoSizedImage.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
import React, {PureComponent} from 'react';
import {Image, Dimensions} from 'react-native';
const {width} = Dimensions.get('window');
const baseStyle = {
backgroundColor: 'transparent',
};
export default class AutoSizedImage extends PureComponent {
constructor(props) {
super(props);
this.state = {
// set width 1 is for preventing the warning
// You must specify a width and height for the image %s
width: this.props.style.width || 1,
height: this.props.style.height || 1,
};
}
componentDidMount() {
//avoid repaint if width/height is given
if (this.props.style.width || this.props.style.height) {
return;
}
Image.getSize(this.props.source.uri, (w, h) => {
this.setState({width: w, height: h});
});
}
render() {
const finalSize = {};
if (this.state.width > width) {
finalSize.width = width;
const ratio = width / this.state.width;
finalSize.height = this.state.height * ratio;
}
const style = Object.assign(
baseStyle,
this.props.style,
this.state,
finalSize
);
let source = {};
if (!finalSize.width || !finalSize.height) {
source = Object.assign(source, this.props.source, this.state);
} else {
source = Object.assign(source, this.props.source, finalSize);
}
return <Image style={style} source={source} />;
}
}