-
Notifications
You must be signed in to change notification settings - Fork 1
/
adjustToView.ts
72 lines (64 loc) · 2.21 KB
/
adjustToView.ts
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
import {Platform} from 'react-native';
export type Dimensions = {width: number; height: number};
export type Rect = {
top: number;
left: number;
height: number;
width: number;
};
const adjustToView =
Platform.OS === 'ios'
? (frame: Dimensions, view: Dimensions) => {
const widthRatio = view.width / frame.width;
const heightRatio = view.height / frame.height;
return {
adjustPoint: (point: {x: number; y: number}) => ({
x: point.x * widthRatio,
y: point.y * heightRatio,
}),
adjustRect(rect: Rect): Rect {
return {
left: rect.left * widthRatio,
top: rect.top * heightRatio,
width: rect.width * widthRatio,
height: rect.height * heightRatio,
};
},
};
}
: (frame: Dimensions, view: Dimensions) => {
'worklet';
const {width, height} = view;
const aspectRatio = width / height;
const frameWidth = frame.width;
const frameHeight = frame.height;
const frameAspectRatio = frameWidth / frameHeight;
let widthRatio: number;
let heightRatio: number;
let offsetX = 0;
let offsetY = 0;
if (frameAspectRatio < aspectRatio) {
widthRatio = width / frameWidth;
const croppedFrameHeight = aspectRatio * frameWidth;
offsetY = (frameHeight - croppedFrameHeight) / 2;
heightRatio = height / croppedFrameHeight;
} else {
heightRatio = height / frameHeight;
const croppedFrameWidth = aspectRatio * frameHeight;
offsetX = (frameWidth - croppedFrameWidth) / 2;
widthRatio = width / croppedFrameWidth;
}
return {
adjustPoint: (point: {x: number; y: number}) => ({
x: (point.x - offsetX) * widthRatio,
y: (point.y - offsetY) * heightRatio,
}),
adjustRect: (rect: Rect) => ({
top: (rect.top - offsetY) * heightRatio,
left: (rect.left - offsetX) * widthRatio,
height: rect.height * heightRatio,
width: rect.width * widthRatio,
}),
};
};
export default adjustToView;