forked from ihor/react-native-scalable-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (89 loc) · 2.79 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import React from 'react';
import PropTypes from 'prop-types';
import { Image, TouchableOpacity, ImageBackground } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
export default class ScalableImage extends React.Component {
constructor(props) {
super(props);
this.state = {
size: {
width: null,
height: null,
}
};
this.mounted = false;
}
componentDidMount() {
this.mounted = true;
this.onProps(this.props);
}
componentWillUnmount() {
this.mounted = false;
}
componentWillReceiveProps(nextProps) {
this.onProps(nextProps);
}
onProps(props) {
if (props.source.uri) {
const source = props.source.uri ? props.source.uri : props.source;
Image.getSize(source, (width, height) => this.adjustSize(width, height, props), console.log);
}
else {
const source = resolveAssetSource(props.source);
this.adjustSize(source.width, source.height, props);
}
}
adjustSize(sourceWidth, sourceHeight, props) {
const { width, height, maxWidth, maxHeight } = props;
let ratio = 1;
if (width && height) {
ratio = Math.min(width / sourceWidth, height / sourceHeight);
}
else if (width) {
ratio = width / sourceWidth;
}
else if (height) {
ratio = height / sourceHeight;
}
// Deprecated stuff. Added the PR by mistake. You should use only width and height props
if (maxWidth && sourceWidth * ratio > maxWidth) {
ratio = maxWidth / sourceWidth;
}
if (maxHeight && sourceHeight * ratio > maxHeight) {
ratio = maxHeight / sourceHeight;
}
if (this.mounted) {
this.setState({
size: {
width: sourceWidth * ratio,
height: sourceHeight * ratio
}
}, () => this.props.onSize(this.state.size));
}
}
render() {
const ImageComponent = this.props.background
? ImageBackground
: Image;
const image = <ImageComponent { ...this.props } style={[this.props.style, this.state.size]}/>;
if (!this.props.onPress) {
return image;
}
return (
<TouchableOpacity onPress={this.props.onPress}>
{image}
</TouchableOpacity>
);
}
}
ScalableImage.propTypes = {
width: PropTypes.number,
height: PropTypes.number,
onPress: PropTypes.func,
onSize: PropTypes.func,
background: PropTypes.bool,
};
ScalableImage.defaultProps = {
background: false,
onSize: size => {}
};