This repository was archived by the owner on Sep 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathimage-viewer.component.tsx
714 lines (634 loc) · 20.6 KB
/
image-viewer.component.tsx
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import * as React from 'react';
import {
Animated,
CameraRoll,
Dimensions,
I18nManager,
Image,
PanResponder,
Platform,
Text,
TouchableHighlight,
TouchableOpacity,
TouchableWithoutFeedback,
View,
ViewStyle
} from 'react-native';
import ImageZoom from 'react-native-image-pan-zoom';
import styles from './image-viewer.style';
import { IImageInfo, IImageSize, Props, State } from './image-viewer.type';
export default class ImageViewer extends React.Component<Props, State> {
public static defaultProps = new Props();
public state = new State();
// 背景透明度渐变动画
private fadeAnim = new Animated.Value(0);
// 当前基准位置
private standardPositionX = 0;
// 整体位移,用来切换图片用
private positionXNumber = 0;
private positionX = new Animated.Value(0);
private width = 0;
private height = 0;
private styles = styles(0, 0, 'transparent');
// 是否执行过 layout. fix 安卓不断触发 onLayout 的 bug
private hasLayout = false;
// 记录已加载的图片 index
private loadedIndex = new Map<number, boolean>();
private handleLongPressWithIndex = new Map<number, any>();
private imageRefs: any[] = [];
public componentDidMount() {
this.init(this.props);
}
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
if (nextProps.index !== prevState.prevIndexProp) {
return { currentShowIndex: nextProps.index, prevIndexProp: nextProps.index };
}
return null;
}
public componentDidUpdate(prevProps: Props, prevState: State) {
if (prevProps.index !== this.props.index) {
// 立刻预加载要看的图
this.loadImage(this.props.index || 0);
this.jumpToCurrentImage();
// 显示动画
Animated.timing(this.fadeAnim, {
toValue: 1,
duration: 200,
useNativeDriver: !!this.props.useNativeDriver
}).start();
}
}
/**
* props 有变化时执行
*/
public init(nextProps: Props) {
if (nextProps.imageUrls.length === 0) {
// 隐藏时候清空
this.fadeAnim.setValue(0);
return this.setState(new State());
}
// 给 imageSizes 塞入空数组
const imageSizes: IImageSize[] = [];
nextProps.imageUrls.forEach(imageUrl => {
imageSizes.push({
width: imageUrl.width || 0,
height: imageUrl.height || 0,
status: 'loading'
});
});
this.setState(
{
currentShowIndex: nextProps.index,
prevIndexProp: nextProps.index || 0,
imageSizes
},
() => {
// 立刻预加载要看的图
this.loadImage(nextProps.index || 0);
this.jumpToCurrentImage();
// 显示动画
Animated.timing(this.fadeAnim, {
toValue: 1,
duration: 200,
useNativeDriver: !!nextProps.useNativeDriver
}).start();
}
);
}
/**
* reset Image scale and position
*/
public resetImageByIndex = (index: number) => {
this.imageRefs[index] && this.imageRefs[index].reset();
};
/**
* 调到当前看图位置
*/
public jumpToCurrentImage() {
// 跳到当前图的位置
this.positionXNumber = this.width * (this.state.currentShowIndex || 0) * (I18nManager.isRTL ? 1 : -1);
this.standardPositionX = this.positionXNumber;
this.positionX.setValue(this.positionXNumber);
}
/**
* 加载图片,主要是获取图片长与宽
*/
public loadImage(index: number) {
if (!this!.state!.imageSizes![index]) {
return;
}
if (this.loadedIndex.has(index)) {
return;
}
this.loadedIndex.set(index, true);
const image = this.props.imageUrls[index];
const imageStatus = { ...this!.state!.imageSizes![index] };
// 保存 imageSize
const saveImageSize = () => {
// 如果已经 success 了,就不做处理
if (this!.state!.imageSizes![index] && this!.state!.imageSizes![index].status !== 'loading') {
return;
}
const imageSizes = this!.state!.imageSizes!.slice();
imageSizes[index] = imageStatus;
this.setState({ imageSizes });
};
if (this!.state!.imageSizes![index].status === 'success') {
// 已经加载过就不会加载了
return;
}
// 如果已经有宽高了,直接设置为 success
if (this!.state!.imageSizes![index].width > 0 && this!.state!.imageSizes![index].height > 0) {
imageStatus.status = 'success';
saveImageSize();
return;
}
// 是否加载完毕了图片大小
const sizeLoaded = false;
// 是否加载完毕了图片
let imageLoaded = false;
// Tagged success if url is started with file:, or not set yet(for custom source.uri).
if (!image.url || image.url.startsWith(`file:`)) {
imageLoaded = true;
}
// 如果已知源图片宽高,直接设置为 success
if (image.width && image.height) {
if (this.props.enablePreload && imageLoaded === false) {
Image.prefetch(image.url);
}
imageStatus.width = image.width;
imageStatus.height = image.height;
imageStatus.status = 'success';
saveImageSize();
return;
}
Image.getSize(
image.url,
(width: number, height: number) => {
imageStatus.width = width;
imageStatus.height = height;
imageStatus.status = 'success';
saveImageSize();
},
() => {
try {
const data = (Image as any).resolveAssetSource(image.props.source);
imageStatus.width = data.width;
imageStatus.height = data.height;
imageStatus.status = 'success';
saveImageSize();
} catch (newError) {
// Give up..
imageStatus.status = 'fail';
saveImageSize();
}
}
);
}
/**
* 预加载图片
*/
public preloadImage = (index: number) => {
if (index < this.state.imageSizes!.length) {
this.loadImage(index + 1);
}
};
/**
* 触发溢出水平滚动
*/
public handleHorizontalOuterRangeOffset = (offsetX: number = 0) => {
this.positionXNumber = this.standardPositionX + offsetX;
this.positionX.setValue(this.positionXNumber);
const offsetXRTL = !I18nManager.isRTL ? offsetX : -offsetX;
if (offsetXRTL < 0) {
if (this!.state!.currentShowIndex || 0 < this.props.imageUrls.length - 1) {
this.loadImage((this!.state!.currentShowIndex || 0) + 1);
}
} else if (offsetXRTL > 0) {
if (this!.state!.currentShowIndex || 0 > 0) {
this.loadImage((this!.state!.currentShowIndex || 0) - 1);
}
}
};
/**
* 手势结束,但是没有取消浏览大图
*/
public handleResponderRelease = (vx: number = 0) => {
const vxRTL = I18nManager.isRTL ? -vx : vx;
const isLeftMove = I18nManager.isRTL
? this.positionXNumber - this.standardPositionX < -(this.props.flipThreshold || 0)
: this.positionXNumber - this.standardPositionX > (this.props.flipThreshold || 0);
const isRightMove = I18nManager.isRTL
? this.positionXNumber - this.standardPositionX > (this.props.flipThreshold || 0)
: this.positionXNumber - this.standardPositionX < -(this.props.flipThreshold || 0);
if (vxRTL > 0.7) {
// 上一张
this.goBack.call(this);
// 这里可能没有触发溢出滚动,为了防止图片不被加载,调用加载图片
if (this.state.currentShowIndex || 0 > 0) {
this.loadImage((this.state.currentShowIndex || 0) - 1);
}
return;
} else if (vxRTL < -0.7) {
// 下一张
this.goNext.call(this);
if (this.state.currentShowIndex || 0 < this.props.imageUrls.length - 1) {
this.loadImage((this.state.currentShowIndex || 0) + 1);
}
return;
}
if (isLeftMove) {
// 上一张
this.goBack.call(this);
} else if (isRightMove) {
// 下一张
this.goNext.call(this);
return;
} else {
// 回到之前的位置
this.resetPosition.call(this);
return;
}
};
/**
* 到上一张
*/
public goBack = () => {
if (this.state.currentShowIndex === 0) {
// 回到之前的位置
this.resetPosition.call(this);
return;
}
this.positionXNumber = !I18nManager.isRTL
? this.standardPositionX + this.width
: this.standardPositionX - this.width;
this.standardPositionX = this.positionXNumber;
Animated.timing(this.positionX, {
toValue: this.positionXNumber,
duration: this.props.pageAnimateTime,
useNativeDriver: !!this.props.useNativeDriver
}).start();
const nextIndex = (this.state.currentShowIndex || 0) - 1;
this.loadImage(nextIndex);
this.setState(
{
currentShowIndex: nextIndex
},
() => {
if (this.props.onChange) {
this.props.onChange(this.state.currentShowIndex);
}
}
);
};
/**
* 到下一张
*/
public goNext = () => {
if (this.state.currentShowIndex === this.props.imageUrls.length - 1) {
// 回到之前的位置
this.resetPosition.call(this);
return;
}
this.positionXNumber = !I18nManager.isRTL
? this.standardPositionX - this.width
: this.standardPositionX + this.width;
this.standardPositionX = this.positionXNumber;
Animated.timing(this.positionX, {
toValue: this.positionXNumber,
duration: this.props.pageAnimateTime,
useNativeDriver: !!this.props.useNativeDriver
}).start();
const nextIndex = (this.state.currentShowIndex || 0) + 1;
this.loadImage(nextIndex);
this.setState(
{
currentShowIndex: nextIndex
},
() => {
if (this.props.onChange) {
this.props.onChange(this.state.currentShowIndex);
}
}
);
};
/**
* 回到原位
*/
public resetPosition() {
this.positionXNumber = this.standardPositionX;
Animated.timing(this.positionX, {
toValue: this.standardPositionX,
duration: 150,
useNativeDriver: !!this.props.useNativeDriver
}).start();
}
/**
* 长按
*/
public handleLongPress = (image: IImageInfo) => {
if (this.props.saveToLocalByLongPress) {
// 出现保存到本地的操作框
this.setState({ isShowMenu: true });
}
if (this.props.onLongPress) {
this.props.onLongPress(image);
}
};
/**
* 单击
*/
public handleClick = () => {
if (this.props.onClick) {
this.props.onClick(this.handleCancel, this.state.currentShowIndex);
}
};
/**
* 双击
*/
public handleDoubleClick = () => {
if (this.props.onDoubleClick) {
this.props.onDoubleClick(this.handleCancel);
}
};
/**
* 退出
*/
public handleCancel = () => {
this.hasLayout = false;
if (this.props.onCancel) {
this.props.onCancel();
}
};
/**
* 完成布局
*/
public handleLayout = (event: any) => {
if (event.nativeEvent.layout.width !== this.width) {
this.hasLayout = true;
this.width = event.nativeEvent.layout.width;
this.height = event.nativeEvent.layout.height;
this.styles = styles(this.width, this.height, this.props.backgroundColor || 'transparent');
// 强制刷新
this.forceUpdate();
this.jumpToCurrentImage();
}
};
/**
* 获得整体内容
*/
public getContent() {
// 获得屏幕宽高
const screenWidth = this.width;
const screenHeight = this.height;
const ImageElements = this.props.imageUrls.map((image, index) => {
if ((this.state.currentShowIndex || 0) > index + 1 || (this.state.currentShowIndex || 0) < index - 1) {
return <View key={index} style={{ width: screenWidth, height: screenHeight }} />;
}
if (!this.handleLongPressWithIndex.has(index)) {
this.handleLongPressWithIndex.set(index, this.handleLongPress.bind(this, image));
}
let width = this!.state!.imageSizes![index] && this!.state!.imageSizes![index].width;
let height = this.state.imageSizes![index] && this.state.imageSizes![index].height;
const imageInfo = this.state.imageSizes![index];
if (!imageInfo || !imageInfo.status) {
return <View key={index} style={{ width: screenWidth, height: screenHeight }} />;
}
// 如果宽大于屏幕宽度,整体缩放到宽度是屏幕宽度
if (width > screenWidth) {
const widthPixel = screenWidth / width;
width *= widthPixel;
height *= widthPixel;
}
// 如果此时高度还大于屏幕高度,整体缩放到高度是屏幕高度
if (height > screenHeight) {
const HeightPixel = screenHeight / height;
width *= HeightPixel;
height *= HeightPixel;
}
const Wrapper = ({ children, ...others }: any) => (
<ImageZoom
cropWidth={this.width}
cropHeight={this.height}
maxOverflow={this.props.maxOverflow}
horizontalOuterRangeOffset={this.handleHorizontalOuterRangeOffset}
responderRelease={this.handleResponderRelease}
onMove={this.props.onMove}
onLongPress={this.handleLongPressWithIndex.get(index)}
onClick={this.handleClick}
onDoubleClick={this.handleDoubleClick}
enableSwipeDown={this.props.enableSwipeDown}
swipeDownThreshold={this.props.swipeDownThreshold}
onSwipeDown={this.handleSwipeDown}
pinchToZoom={this.props.enableImageZoom}
enableDoubleClickZoom={this.props.enableImageZoom}
doubleClickInterval={this.props.doubleClickInterval}
{...others}
>
{children}
</ImageZoom>
);
switch (imageInfo.status) {
case 'loading':
return (
<Wrapper
key={index}
style={{
...this.styles.modalContainer,
...this.styles.loadingContainer
}}
imageWidth={screenWidth}
imageHeight={screenHeight}
>
<View style={this.styles.loadingContainer}>{this!.props!.loadingRender!()}</View>
</Wrapper>
);
case 'success':
if (!image.props) {
image.props = {};
}
if (!image.props.style) {
image.props.style = {};
}
image.props.style = {
...this.styles.imageStyle, // User config can override above.
...image.props.style,
width,
height
};
if (typeof image.props.source === 'number') {
// source = require(..), doing nothing
} else {
if (!image.props.source) {
image.props.source = {};
}
image.props.source = {
uri: image.url,
...image.props.source
};
}
if (this.props.enablePreload) {
this.preloadImage(this.state.currentShowIndex || 0);
}
return (
<ImageZoom
key={index}
ref={el => (this.imageRefs[index] = el)}
cropWidth={this.width}
cropHeight={this.height}
maxOverflow={this.props.maxOverflow}
horizontalOuterRangeOffset={this.handleHorizontalOuterRangeOffset}
responderRelease={this.handleResponderRelease}
onMove={this.props.onMove}
onLongPress={this.handleLongPressWithIndex.get(index)}
onClick={this.handleClick}
onDoubleClick={this.handleDoubleClick}
imageWidth={width}
imageHeight={height}
enableSwipeDown={this.props.enableSwipeDown}
swipeDownThreshold={this.props.swipeDownThreshold}
onSwipeDown={this.handleSwipeDown}
panToMove={!this.state.isShowMenu}
pinchToZoom={this.props.enableImageZoom && !this.state.isShowMenu}
enableDoubleClickZoom={this.props.enableImageZoom && !this.state.isShowMenu}
doubleClickInterval={this.props.doubleClickInterval}
minScale={this.props.minScale}
maxScale={this.props.maxScale}
>
{this!.props!.renderImage!(image.props)}
</ImageZoom>
);
case 'fail':
return (
<Wrapper
key={index}
style={this.styles.modalContainer}
imageWidth={this.props.failImageSource ? this.props.failImageSource.width : screenWidth}
imageHeight={this.props.failImageSource ? this.props.failImageSource.height : screenHeight}
>
{this.props.failImageSource &&
this!.props!.renderImage!({
source: {
uri: this.props.failImageSource.url
},
style: {
width: this.props.failImageSource.width,
height: this.props.failImageSource.height
}
})}
</Wrapper>
);
}
});
return (
<Animated.View style={{ zIndex: 9 }}>
<Animated.View style={{ ...this.styles.container, opacity: this.fadeAnim }}>
{this!.props!.renderHeader!(this.state.currentShowIndex)}
<View style={this.styles.arrowLeftContainer}>
<TouchableWithoutFeedback onPress={this.goBack}>
<View>{this!.props!.renderArrowLeft!()}</View>
</TouchableWithoutFeedback>
</View>
<View style={this.styles.arrowRightContainer}>
<TouchableWithoutFeedback onPress={this.goNext}>
<View>{this!.props!.renderArrowRight!()}</View>
</TouchableWithoutFeedback>
</View>
<Animated.View
style={{
...this.styles.moveBox,
transform: [{ translateX: this.positionX }],
width: this.width * this.props.imageUrls.length
}}
>
{ImageElements}
</Animated.View>
{this!.props!.renderIndicator!((this.state.currentShowIndex || 0) + 1, this.props.imageUrls.length)}
{this.props.imageUrls[this.state.currentShowIndex || 0] &&
this.props.imageUrls[this.state.currentShowIndex || 0].originSizeKb &&
this.props.imageUrls[this.state.currentShowIndex || 0].originUrl && (
<View style={this.styles.watchOrigin}>
<TouchableOpacity style={this.styles.watchOriginTouchable}>
<Text style={this.styles.watchOriginText}>查看原图(2M)</Text>
</TouchableOpacity>
</View>
)}
<View style={[{ bottom: 0, position: 'absolute', zIndex: 9 }, this.props.footerContainerStyle]}>
{this!.props!.renderFooter!(this.state.currentShowIndex || 0)}
</View>
</Animated.View>
</Animated.View>
);
}
/**
* 保存当前图片到本地相册
*/
public saveToLocal = () => {
if (!this.props.onSave) {
CameraRoll.saveToCameraRoll(this.props.imageUrls[this.state.currentShowIndex || 0].url);
this!.props!.onSaveToCamera!(this.state.currentShowIndex);
} else {
this.props.onSave(this.props.imageUrls[this.state.currentShowIndex || 0].url);
}
this.setState({ isShowMenu: false });
};
public getMenu() {
if (!this.state.isShowMenu) {
return null;
}
if (this.props.menus) {
return (
<View style={this.styles.menuContainer}>
{this.props.menus({ cancel: this.handleLeaveMenu, saveToLocal: this.saveToLocal })}
</View>
);
}
return (
<View style={this.styles.menuContainer}>
<View style={this.styles.menuShadow} />
<View style={this.styles.menuContent}>
<TouchableHighlight underlayColor="#F2F2F2" onPress={this.saveToLocal} style={this.styles.operateContainer}>
<Text style={this.styles.operateText}>{this.props.menuContext.saveToLocal}</Text>
</TouchableHighlight>
<TouchableHighlight
underlayColor="#F2F2F2"
onPress={this.handleLeaveMenu}
style={this.styles.operateContainer}
>
<Text style={this.styles.operateText}>{this.props.menuContext.cancel}</Text>
</TouchableHighlight>
</View>
</View>
);
}
public handleLeaveMenu = () => {
this.setState({ isShowMenu: false });
};
public handleSwipeDown = () => {
if (this.props.onSwipeDown) {
this.props.onSwipeDown();
}
this.handleCancel();
};
public render() {
let childs: React.ReactElement<any> = null as any;
childs = (
<View>
{this.getContent()}
{this.getMenu()}
</View>
);
return (
<View
onLayout={this.handleLayout}
style={{
flex: 1,
overflow: 'hidden',
...this.props.style
}}
>
{childs}
</View>
);
}
}