forked from PeterStaev/nativescript-image-swipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-swipe.android.ts
543 lines (438 loc) · 20.1 KB
/
image-swipe.android.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
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
/*! *****************************************************************************
Copyright (c) 2019 Tangra Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************** */
import { GestureTypes } from "ui/gestures";
import { ImageSwipeBase, allowZoomProperty, itemsProperty, pageNumberProperty } from "./image-swipe-common";
// These constants specify the mode that we're in
const MODE_NONE = 0;
const MODE_DRAG = 1;
const MODE_ZOOM = 2;
const ALL_GESTURE_TYPES: GestureTypes[] = [
GestureTypes.doubleTap,
GestureTypes.longPress,
GestureTypes.pan,
GestureTypes.pinch,
GestureTypes.rotation,
GestureTypes.swipe,
GestureTypes.tap,
GestureTypes.touch
];
const enum Orientation {
Portrait = 0,
Landscape = 1,
PortraitReverse = 2,
LandscapeReverse = 3
}
export * from "./image-swipe-common";
export class ImageSwipe extends ImageSwipeBase {
public nativeView: StateViewPager;
public createNativeView() {
const stateViewPager = new StateViewPager(this._context);
stateViewPager.setOffscreenPageLimit(1);
const adapter = new ImageSwipePageAdapter(new WeakRef(this));
(stateViewPager as any).adapter = adapter;
stateViewPager.setAdapter(adapter);
const imageSwipePageListener = new ImageSwipePageChangeListener(new WeakRef(this));
(stateViewPager as any).imageSwipePageListener = imageSwipePageListener;
stateViewPager.setOnPageChangeListener(imageSwipePageListener);
if (this.pageNumber !== null && this.pageNumber !== undefined) {
stateViewPager.setCurrentItem(this.pageNumber);
}
return stateViewPager;
}
public initNativeView() {
super.initNativeView();
const nativeView = this.nativeView as any;
nativeView.adapter.owner = new WeakRef(this);
nativeView.imageSwipePageListener.owner = new WeakRef(this);
}
get android(): StateViewPager {
return this.nativeView;
}
public refresh() {
if (this.nativeView) {
this.nativeView.getAdapter().notifyDataSetChanged();
}
// Coerce selected index after we have set items to native view.
pageNumberProperty.coerce(this);
}
public [allowZoomProperty.setNative](value: boolean) {
const currentImage = this.nativeView.findViewWithTag("Item" + this.pageNumber) as ZoomImageView;
if (currentImage) {
// reset if there is a current image. This method is called if the initial value differs from the defaultValue (true)
// before an actual image view has been created
currentImage.reset();
}
}
public [pageNumberProperty.setNative](value: number) {
this.nativeView.setCurrentItem(value);
}
public [itemsProperty.setNative](value: any) {
this.refresh();
}
}
@Interfaces([androidx.viewpager.widget.ViewPager.OnPageChangeListener])
class ImageSwipePageChangeListener extends java.lang.Object implements androidx.viewpager.widget.ViewPager.OnPageChangeListener {
constructor(private owner: WeakRef<ImageSwipe>) {
super();
return global.__native(this);
}
public onPageSelected(index: number) {
const owner = this.owner.get();
owner.pageNumber = index;
owner.notify({
eventName: ImageSwipe.pageChangedEvent,
object: owner,
page: index
});
// For Angular it happens that this is triggered before the native view is initialized
if (!owner.nativeViewProtected) {
return;
}
let preloadedImageView: ZoomImageView;
preloadedImageView = owner.nativeViewProtected.findViewWithTag("Item" + (index - 1).toString()) as ZoomImageView;
if (preloadedImageView) {
preloadedImageView.reset();
}
preloadedImageView = owner.nativeViewProtected.findViewWithTag("Item" + (index + 1).toString()) as ZoomImageView;
if (preloadedImageView) {
preloadedImageView.reset();
}
}
public onPageScrolled() {
// Currently not used
}
public onPageScrollStateChanged() {
// Currently not used
}
}
class StateViewPager extends androidx.viewpager.widget.ViewPager {
private _allowScrollIn: boolean = true;
constructor(context: android.content.Context) {
super(context);
return global.__native(this);
}
public onInterceptTouchEvent(event: android.view.MotionEvent): boolean {
if (this._allowScrollIn) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public setAllowScrollIn(allowScrollIn: boolean) {
this._allowScrollIn = allowScrollIn;
}
}
class ImageSwipePageAdapter extends androidx.viewpager.widget.PagerAdapter {
constructor(private owner: WeakRef<ImageSwipe>) {
super();
return global.__native(this);
}
public instantiateItem(container: android.view.ViewGroup, position: number): java.lang.Object {
const owner = this.owner.get();
const imageUrl = owner._getDataItem(position)[owner.imageUrlProperty];
const params = new androidx.viewpager.widget.ViewPager.LayoutParams();
params.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
params.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
const imageView = new ZoomImageView(this.owner);
imageView.setLayoutParams(params);
imageView.setTag("Item" + position.toString());
const that = new WeakRef(owner);
imageView.setOnCanScrollChangeListener(new OnCanScrollChangeListener({
onCanScrollChanged: (canScroll: boolean) => {
that.get().nativeViewProtected.setAllowScrollIn(canScroll);
}
}));
const progressBar = new android.widget.ProgressBar(owner._context);
progressBar.setLayoutParams(params);
progressBar.setVisibility(android.view.View.GONE);
progressBar.setIndeterminate(true);
const layout = new android.widget.LinearLayout(owner._context);
layout.setLayoutParams(params);
layout.setOrientation(android.widget.LinearLayout.VERTICAL);
layout.addView(progressBar);
layout.addView(imageView);
container.addView(layout);
progressBar.setVisibility(android.view.View.VISIBLE);
const image: android.graphics.Bitmap = ImageSwipeBase._imageCache.get(imageUrl);
if (image) {
imageView.setImageBitmap(image);
progressBar.setVisibility(android.view.View.GONE);
}
else {
ImageSwipeBase._imageCache.push({
key: imageUrl,
url: imageUrl,
completed: (bitmap: android.graphics.Bitmap) => {
imageView.setImageBitmap(bitmap);
progressBar.setVisibility(android.view.View.GONE);
}
});
}
return layout;
}
public destroyItem(container: android.view.ViewGroup, position: number, object: any) {
container.removeView(object as android.view.View);
}
public getCount(): number {
const owner = this.owner.get();
return owner && owner.items ? owner.items.length : 0;
}
public isViewFromObject(view: android.view.View, object: java.lang.Object): boolean {
return view === object;
}
}
class ZoomImageView extends android.widget.ImageView {
private _scaleFactor = [1]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
private _minScaleFactor = [1]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
private _detector: android.view.ScaleGestureDetector;
private _mode: number = 0;
private _dragged = false;
private _image: android.graphics.Bitmap;
// These two variables keep track of the X and Y coordinate of the finger when it first
// touches the screen
private _startX: number = 0;
private _startY: number = 0;
// These two variables keep track of the amount we need to translate the canvas along the X and the Y coordinate
private _translateX = [0]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
private _translateY = [0]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
// These two variables keep track of the total amount we translated the X and Y coordinates and confirmed it (finger up).
private _totalTranslateX = [0]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
private _totalTranslateY = [0]; // HACK: for some reason only number private variable does not work, use Array and set the value to the first item in the array.
private _orientationChangeListener: OrientationListener;
private _onCanScrollChangeListener: OnCanScrollChangeListenerImplementation;
constructor(private _owner: WeakRef<ImageSwipe>) {
super(_owner.get()._context);
const context = _owner.get()._context;
const that = new WeakRef(this);
this._detector = new android.view.ScaleGestureDetector(context, new android.view.ScaleGestureDetector.OnScaleGestureListener({
onScale: (detector: android.view.ScaleGestureDetector): boolean => {
const owner = that.get();
owner.setScaleFactor(owner.getScaleFactor() * detector.getScaleFactor());
return true;
},
onScaleBegin: () => true,
// tslint:disable-next-line:no-empty
onScaleEnd: () => { }
}));
this._orientationChangeListener = new OrientationListener(context, that);
this._orientationChangeListener.enable();
return global.__native(this);
}
public setImageBitmap(image: android.graphics.Bitmap) {
this._image = image;
this.reset();
}
public onTouchEvent(event: android.view.MotionEvent): boolean {
const owner = this._owner.get();
if (owner.allowZoom) {
switch (event.getActionMasked()) {
case android.view.MotionEvent.ACTION_DOWN:
this._mode = MODE_DRAG;
// We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
// amount for each coordinates This works even when we are translating the first time because the initial
// values for these two variables is zero.
this._startX = event.getX();
this._startY = event.getY();
break;
case android.view.MotionEvent.ACTION_MOVE:
const scaleFactor = this.getScaleFactor();
let translateX = this._startX - event.getX();
let translateY = this._startY - event.getY();
const totalTranslateX = this.getTotalTranslateX();
const totalTranslateY = this.getTotalTranslateY();
const height = this.getHeight();
const width = this.getWidth();
const imageHeight = this._image.getHeight();
const imageWidth = this._image.getWidth();
let canScroll = false;
if (Math.max(0, (width - (imageWidth * scaleFactor)) / 2) !== 0) { // Not scaled large enough, we automatically center it in onDraw
translateX = 0;
canScroll = true;
}
else if (totalTranslateX + translateX < 0) { // outside left bounds
translateX = -totalTranslateX;
canScroll = true;
}
else if (totalTranslateX + translateX + width > imageWidth * scaleFactor) { // Outside right bounds
translateX = (imageWidth * scaleFactor) - width - totalTranslateX;
canScroll = true;
}
if (this._onCanScrollChangeListener) {
this._onCanScrollChangeListener.onCanScrollChanged(canScroll);
}
if (Math.max(0, (height - (imageHeight * scaleFactor)) / 2) !== 0) { // Not scaled large enough, we automatically center it in onDraw
translateY = 0;
}
else if (totalTranslateY + translateY < 0) { // outside lower bounds
translateY = -totalTranslateY;
}
else if (totalTranslateY + translateY + height > imageHeight * scaleFactor) { // Outside upper bounds
translateY = (imageHeight * scaleFactor) - height - totalTranslateY;
}
if (translateX !== 0 || translateY !== 0) {
this._dragged = true;
}
this.setTranslateX(translateX);
this.setTranslateY(translateY);
break;
case android.view.MotionEvent.ACTION_POINTER_DOWN:
this._mode = MODE_ZOOM;
break;
case android.view.MotionEvent.ACTION_UP:
this._mode = MODE_NONE;
this._dragged = false;
// All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
// previousTranslate
this.setTotalTranslateX(this.getTotalTranslateX() + this.getTranslateX());
this.setTotalTranslateY(this.getTotalTranslateY() + this.getTranslateY());
this.setTranslateX(0);
this.setTranslateY(0);
break;
case android.view.MotionEvent.ACTION_POINTER_UP:
this._mode = MODE_DRAG;
// This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
// and previousTranslateY when the second finger goes up
this.setTotalTranslateX(this.getTotalTranslateX() + this.getTranslateX());
this.setTotalTranslateY(this.getTotalTranslateY() + this.getTranslateY());
this.setTranslateX(0);
this.setTranslateY(0);
break;
}
this._detector.onTouchEvent(event);
if ((this._mode === MODE_DRAG && this._dragged)
|| this._mode === MODE_ZOOM) {
this.invalidate();
}
}
for (const gestureType of ALL_GESTURE_TYPES) {
for (const observer of owner.getGestureObservers(gestureType) || []) {
observer.androidOnTouchEvent(event);
}
}
return true;
}
public onDraw(canvas: android.graphics.Canvas) {
canvas.save();
const scaleFactor = this.getScaleFactor();
// We're going to scale the X and Y coordinates by the same amount
canvas.scale(scaleFactor, scaleFactor);
canvas.translate(-(this.getTotalTranslateX() + this.getTranslateX()) / scaleFactor, -(this.getTotalTranslateY() + this.getTranslateY()) / scaleFactor);
if (this._image) {
canvas.drawBitmap(this._image, Math.max(0, (this.getWidth() - (this._image.getWidth() * scaleFactor)) / 2) / scaleFactor, Math.max(0, (this.getHeight() - (this._image.getHeight() * scaleFactor)) / 2) / scaleFactor, new android.graphics.Paint());
}
canvas.restore();
}
public setOnCanScrollChangeListener(listener: OnCanScrollChangeListenerImplementation) {
this._onCanScrollChangeListener = listener;
}
public setMinScaleFactor(scaleFactor: number) {
this._minScaleFactor[0] = scaleFactor;
}
public getMinScaleFactor(): number {
return this._minScaleFactor[0];
}
public setScaleFactor(scaleFactor: number) {
this._scaleFactor[0] = Math.max(this.getMinScaleFactor(), scaleFactor);
}
public getScaleFactor(): number {
return this._scaleFactor[0];
}
public setTranslateX(translate: number) {
this._translateX[0] = translate;
}
public getTranslateX(): number {
return this._translateX[0];
}
public setTranslateY(translate: number) {
this._translateY[0] = translate;
}
public getTranslateY(): number {
return this._translateY[0];
}
public setTotalTranslateX(translate: number) {
this._totalTranslateX[0] = translate;
}
public getTotalTranslateX(): number {
return this._totalTranslateX[0];
}
public setTotalTranslateY(translate: number) {
this._totalTranslateY[0] = translate;
}
public getTotalTranslateY(): number {
return this._totalTranslateY[0];
}
public reset(isDelayIn?: boolean) {
setTimeout(() => {
if (this && this._image) {
try {
this.setTotalTranslateX(0);
this.setTotalTranslateY(0);
this.setTranslateX(0);
this.setTranslateY(0);
this.setMinScaleFactor(Math.min(this.getHeight() / this._image.getHeight(), this.getWidth() / this._image.getWidth()));
this.setScaleFactor(this.getMinScaleFactor());
this.invalidate();
}
catch (e) {
// Do nothing
}
}
}, (isDelayIn ? 750 : 10));
}
}
class OrientationListener extends android.view.OrientationEventListener {
private _zoomImageView: WeakRef<ZoomImageView>;
private _previousOrientation: Orientation;
constructor(context: android.content.Context, zoomImageView: WeakRef<ZoomImageView>) {
super(context);
this._zoomImageView = zoomImageView;
this._previousOrientation = Orientation.Portrait;
return global.__native(this);
}
public onOrientationChanged(orientation: number) {
const zoomImageView: ZoomImageView = this._zoomImageView.get();
let orientationChanged = false;
let currentOrientation: Orientation;
if (orientation <= 45) {
currentOrientation = Orientation.Portrait;
} else if (orientation <= 135) {
currentOrientation = Orientation.LandscapeReverse;
} else if (orientation <= 225) {
currentOrientation = Orientation.PortraitReverse;
} else if (orientation <= 315) {
currentOrientation = Orientation.Landscape;
} else {
currentOrientation = Orientation.Portrait;
}
if (currentOrientation !== this._previousOrientation) {
this._previousOrientation = currentOrientation;
orientationChanged = true;
}
if (zoomImageView && orientationChanged) {
zoomImageView.reset(true);
}
}
}
interface OnCanScrollChangeListenerImplementation {
onCanScrollChanged(canScroll: boolean): void;
}
class OnCanScrollChangeListener extends java.lang.Object implements OnCanScrollChangeListenerImplementation {
private _implementation: OnCanScrollChangeListenerImplementation;
constructor(implementation: OnCanScrollChangeListenerImplementation) {
super();
this._implementation = implementation;
return global.__native(this);
}
public onCanScrollChanged(canScroll: boolean) {
this._implementation.onCanScrollChanged(canScroll);
}
}