-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
43 lines (36 loc) · 1.22 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
import React, { useState, useMemo, useEffect } from "react";
import { Image, StyleSheet } from "react-native";
import PropTypes from "prop-types";
function AutoScaleImage({ style, uri, ...restProps }: Props) {
const flattenedStyles = useMemo(() => StyleSheet.flatten(style), [style]);
if (
typeof flattenedStyles.width !== "number" &&
typeof flattenedStyles.height !== "number"
) {
throw new Error("AutoScaleImage requires either width or height");
}
const [size, setSize] = useState({
width: flattenedStyles.width,
height: flattenedStyles.height
});
useEffect(() => {
if (!flattenedStyles.width || !flattenedStyles.height) {
Image.getSize(uri, (w, h) => {
const ratio = w / h;
setSize({
width: flattenedStyles.width || ratio * flattenedStyles.height || 0,
height: flattenedStyles.height || flattenedStyles.width / ratio || 0
});
});
}
}, [uri, flattenedStyles.width, flattenedStyles.height]);
return <Image source={{ uri }} style={[style, size]} {...restProps} />;
}
AutoScaleImage.propTypes = {
uri: PropTypes.string.isRequired,
style: PropTypes.object
};
AutoScaleImage.defaultProps = {
style: {}
};
export default AutoScaleImage;