forked from vivaxy/react-native-auto-height-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
69 lines (62 loc) · 1.67 KB
/
cache.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
/**
* @since 2017-04-24 20:50:41
* @author vivaxy
*/
import { Image } from 'react-native';
// undocumented but part of react-native; see
// https://github.com/facebook/react-native/issues/5603#issuecomment-297959695
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
/**
* store with
* key: image
* value: {
* width: 100,
* height: 100,
* }
*/
const cache = new Map();
const getImageSizeFromCache = (image) => {
if (typeof image === 'number') {
return cache.get(image);
} else {
return cache.get(image.uri);
}
};
const loadImageSize = (image) => {
return new Promise((resolve, reject) => {
//number indicates import X or require(X) was used (i.e. local file)
if (typeof image === 'number') {
const { width, height } = resolveAssetSource(image);
resolve({ width, height });
} else {
Image.getSize(
image.uri,
(width, height) => {
// success
resolve({ width, height });
},
reject
);
}
});
};
export const getImageSizeFitWidthFromCache = (image, toWidth) => {
const size = getImageSizeFromCache(image);
if (size) {
const { width, height } = size;
return { width: toWidth, height: toWidth * height / width };
}
return {};
};
const getImageSizeMaybeFromCache = async (image) => {
let size = getImageSizeFromCache(image);
if (!size) {
size = await loadImageSize(image);
cache.set(image, size);
}
return size;
};
export const getImageSizeFitWidth = async (image, toWidth) => {
const { width, height } = await getImageSizeMaybeFromCache(image);
return { width: toWidth, height: toWidth * height / width };
};