-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathZoomImageView.java
1292 lines (1168 loc) · 35.9 KB
/
ZoomImageView.java
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.serenegiant.widget;
/*
* ZoomingImageView for Android:
* Copyright(c) 2014-2020 t_saki@serenegiant.com
*
* This class extends ImageView to support zooming/draging/rotating of image with touch.
* You can replace usual ImageView with this class.
*
* File name: ZoomingImageView.java
*/
/*
* 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.
*/
/*
* Usage:
* Double touch and holds while more tha long press timeout, start rotating</br>
* When start rotating, color reversing effect execute as a default visual effect</br>
* You can cancel the default feedback and execute addition feedback in the callback listener</br>
*
* Double touch and pinch in/out zoom the image in/out.
*
* Single touch with move drags the image.
*
* Single touch and hold while more than long press timeouit, reset the zooming/draging/rotaing
* and fit the image in this view.</br>
* You can reset zooming/moving/rotating with calling #reset programmatically
* Limitation of this class:
* This class internally use image matrix to zoom/drag/rotate image,
* therefore you can not set matrix with #setImageMatrix.
* If you set matrix, it is ignored and has no effect.
*
* And the scaleType is fixed to ScaleType.MATRIX. If you set in xml or programmatically other than ScaleType.MATRIX,
* it is ignored and has no effect.
*
* This class requires API level >= 8
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;
/**
* ImageView with zooming/dragging/rotating image with touch
*/
public class ZoomImageView extends ImageView {
private static final boolean DEBUG = false; // TODO for debugging
private static final String TAG = "ZoomImageView";
// constants
/**
* State: idle
*/
private static final int STATE_NON = 0;
/**
* State: wait action
*/
private static final int STATE_WAITING = 1;
/**
* State: dragging
*/
private static final int STATE_DRAGING = 2;
/**
* State: transition state to check starting zoom/rotation
*/
private static final int STATE_CHECKING = 3;
/**
* State: zooming
*/
private static final int STATE_ZOOMING = 4;
/**
* State: Rotating
*/
private static final int STATE_ROTATING = 5;
/**
* default value of maximum zoom scale
*/
private static final float DEFAULT_MAX_SCALE = 8.f;
/**
* default value of minimum zoom scale
*/
private static final float DEFAULT_MIN_SCALE = 0.1f;
/**
* default value without zooming
*/
private static final float DEFAULT_SCALE = 1.f;
/**
* minimum distance between touch positions when start zooming/rotating
*/
private static final float MIN_DISTANCE = 15.f;
private static final float MIN_DISTANCE_SQUARE = MIN_DISTANCE * MIN_DISTANCE;
/**
* limit value to prevent the image disappearing from the view when moving
*/
private static final int MOVE_LIMIT = 50;
/**
* the duration in milliseconds we will wait to start rotating(if multi touched)/reseting(if single touched)
*/
private static final int CHECK_TIMEOUT
= ViewConfiguration.getTapTimeout() + ViewConfiguration.getLongPressTimeout();
/**
* the duration in milliseconds we will wait to reset reversing the color of image
*/
private static final int REVERSING_TIMEOUT = 100;
/**
* conversion factor from radian to degree
*/
private static final float TO_DEGREE = 57.2957795130823f; // = (1.0f / Math.PI) * 180.0f;
/**
* ColorMatrix data for reversing image
*/
private static final float[] REVERSE = {
-1.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, -1.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, -1.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
};
/**
*
*/
private static final float EPS = 0.1f;
// variables
/**
* flag for save/restore state of this view
*/
private boolean mIsRestored;
/**
* Matrix for zooming/moving/rotating
*/
protected final Matrix mImageMatrix = new Matrix();
/**
* flag when mImageMatrix is changed(for updating Matrix cache)
*/
protected boolean mImageMatrixChanged;
/**
* Matrix cache of mImageMatrix elements</br>
* to reduce overhead of JINI call in the Matrix
*/
protected final float[] mMatrixCache = new float[9];
/**
* for save the Matrix when touch operation start
*/
private final Matrix mSavedImageMatrix = new Matrix();
/**
* limit bounds that image can move
*/
private final RectF mLimitRect = new RectF();
/**
* limit line segments tha image can move
*/
private final LineSegment[] mLimitSegments = new LineSegment[4];
/**
* actual size of image in ImageView(copy from ImageView#getDrawable#getBounds)
*/
private final RectF mImageRect = new RectF();
/**
* scaled and moved and rotated corner coordinates of image
* [(left,top),(right,top),(right,bottom),(left.bottom)]
*/
private final float[] mTrans = new float[8];
/**
* touch ids for touch operations
*/
private int mPrimaryId, mSecondaryId;
/**
* x/y coordinates of primary touch point
*/
private float mPrimaryX, mPrimaryY;
/**
* x/y coordinates of second touch for rotation
*/
private float mSecondX, mSecondY;
/**
* x/y coordinates of pivot point for zooming/rotating
*/
private float mPivotX, mPivotY;
/**
* distance between touch points when start multi touch, for calculating zooming scale
*/
private float mTouchDistance;
/**
* current rotating degree
*/
private float mCurrentDegrees;
private boolean mIsRotating;
/**
* Maximum zoom scale
*/
private float mMaxScale = DEFAULT_MAX_SCALE;
/**
* Minimum zoom scale, set in #init as fit the image to this view bounds
*/
private float mMinScale = DEFAULT_MIN_SCALE;
/**
* current state, -1/STATE_NON/STATE_WATING/STATE_DRAGING/STATE_CHECKING
* /STATE_ZOOMING/STATE_ROTATING
*/
private int mState;
/**
* listener for visual/sound feedback on start rotating
*/
private OnStartRotationListener mOnStartRotationListener;
/**
* ColorFilter to reverse the color of the image
* for default visual feedbak on start rotating
*/
private ColorFilter mColorReverseFilter;
/**
* backup of ColorFilter to restore after image color reversing
*/
private ColorFilter mSavedColorFilter;
/**
* Runnable instance to wait starting image reset
*/
private Runnable mWaitImageReset;
/**
* Runnable instance to wait starting rotation
*/
private Runnable mStartCheckRotate;
/**
* Runnable instcance to wait restoring the image color
*/
private Runnable mWaitReverseReset;
/**
* callback listener called when rotation started.
*/
public interface OnStartRotationListener {
/**
* this method is called when rotating starts.</br>
* you will execute feedback something like sound and/or visual effects.
* @param view
* @return if return false, we execute a default visual effect(color reversing)
*/
public boolean onStartRotation(ZoomImageView view);
}
/**
* Runnable to wait restoring the image color
*/
private final class WaitReverseReset implements Runnable {
@Override
public void run() {
resetColorFilter();
}
}
/**
* Runnable to wait resetting the image
*/
private final class WaitImageReset implements Runnable {
@Override
public void run() {
reset();
}
}
/**
* Runnable to wait starting rotation
*/
private final class StartCheckRotate implements Runnable {
@Override
public void run() {
if (mState == STATE_CHECKING) {
setState(STATE_ROTATING);
callOnStartRotationListener();
}
}
}
/**
* class for process to save and restore the view state
*/
public static final class SavedState extends View.BaseSavedState {
private int mState;
private float mMinScale;
private float mCurrentDegrees;
private float[] mMatrixCache = new float[9];
/**
* constractor to restore state
*/
public SavedState(final Parcel in) {
super(in);
readFromParcel(in);
}
/**
* constructor to saved state
*/
public SavedState(final Parcelable superState) {
super(superState);
}
private void readFromParcel(final Parcel in) {
// should read as same order when writing
mState = in.readInt();
mMinScale = in.readFloat();
mCurrentDegrees = in.readFloat();
in.readFloatArray(mMatrixCache);
}
@Override
public void writeToParcel(final Parcel out, final int flags) {
super.writeToParcel(out, flags);
// should write as same order when reading
out.writeInt(mState);
out.writeFloat(mMinScale);
out.writeFloat(mCurrentDegrees);
out.writeFloatArray(mMatrixCache);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(final Parcel source) {
return new SavedState(source);
}
public SavedState[] newArray(final int size) {
return new SavedState[size];
}
};
}
/**
* Constructor for constructing in program
* @param context
*/
public ZoomImageView(final Context context) {
super(context);
// nothing to do now
}
/**
* Constructor for constructing from xml
* @param context
* @param attrs
*/
public ZoomImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
// nothing to do now
}
/**
* Constructor for constructing from xml
* @param context
* @param attrs
* @param defStyle
*/
public ZoomImageView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
// nothing to do now
}
@Override
protected void onDetachedFromWindow() {
clearCallbacks();
super.onDetachedFromWindow();
}
@Override
protected void onRestoreInstanceState(final Parcelable state) {
if (DEBUG) Log.v(TAG, "onRestoreInstanceState:");
if (state instanceof SavedState) {
final SavedState saved = (SavedState)state;
super.onRestoreInstanceState(saved.getSuperState());
mIsRestored = true;
System.arraycopy(saved.mMatrixCache, 0, mMatrixCache, 0, saved.mMatrixCache.length);
mImageMatrix.setValues(mMatrixCache);
mState = saved.mState;
mMinScale = saved.mState;
mCurrentDegrees = saved.mCurrentDegrees;
} else {
super.onRestoreInstanceState(state);
}
}
@Override
protected Parcelable onSaveInstanceState() {
if (DEBUG) Log.v(TAG, "onSaveInstanceState:");
final SavedState saveState = new SavedState(super.onSaveInstanceState());
updateMatrixCache();
saveState.mState = mState;
saveState.mMinScale = mMinScale;
saveState.mCurrentDegrees = mCurrentDegrees;
saveState.mMatrixCache = mMatrixCache;
return saveState;
}
@Override
protected void onConfigurationChanged(final Configuration newConfig) {
if (DEBUG) Log.v(TAG, "onConfigurationChanged:");
super.onConfigurationChanged(newConfig);
mIsRestored = false;
// XXX need something?
}
/**
* set the scale type</br>
* this method ignore the parameter because this class always needs to set ScaleType.MATRIX internally.
*/
@Override
public void setScaleType(final ScaleType scaleType) {
super.setScaleType(ImageView.ScaleType.MATRIX);
Log.w(TAG, "setScaleType: ignore this parameter on ZoomImageView, fixed to ScaleType.MATRIX.");
}
/**
* set the Matrix for image zooming/transforming</br>
* this method ignore the parameter because ZoomImageView needs to set Matrix internally
*/
@Override
public void setImageMatrix(final Matrix matrix) {
super.setImageMatrix(mImageMatrix);
Log.w(TAG, "setScaleType: ignore this parameter on ZoomImageView.");
}
@Override
public void setColorFilter(final ColorFilter cf) {
// save the ColorFilter to restore after default visual feedback on start rotating
mSavedColorFilter = cf;
super.setColorFilter(cf);
}
@Override
protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) {
super.onLayout(changed, left, top, right, bottom);
// if view size(width|height) is zero(the view size not decided yet)
// or no image assigned, skip initialization
if (getWidth() == 0 || getHeight() == 0 || !hasImage()) return;
mState = -1; // reset state
init();
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
// if there is no image, leave to super class
if (!hasImage()) return super.onTouchEvent(event);
final int actionCode = event.getActionMasked(); // >= API8
switch (actionCode) {
case MotionEvent.ACTION_DOWN:
// single touch
startWaiting(event);
return true;
case MotionEvent.ACTION_POINTER_DOWN:
{
// start multi touch, zooming/rotating
switch (mState) {
case STATE_WAITING:
removeCallbacks(mWaitImageReset);
case STATE_DRAGING:
if (event.getPointerCount() > 1) {
startCheck(event);
return true;
}
break;
}
break;
}
case MotionEvent.ACTION_MOVE:
{
// moving with single and multi touch
switch (mState) {
case STATE_WAITING:
if (checkTouchMoved(event)) {
removeCallbacks(mWaitImageReset);
setState(STATE_DRAGING);
return true;
}
break;
case STATE_DRAGING:
if (processDrag(event))
return true;
break;
case STATE_CHECKING:
if (checkTouchMoved(event)) {
startZoom(event);
return true;
}
break;
case STATE_ZOOMING:
if (processZoom(event))
return true;
break;
case STATE_ROTATING:
if (processRotate(event))
return true;
break;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
removeCallbacks(mWaitImageReset);
removeCallbacks(mStartCheckRotate);
resetColorFilter();
case MotionEvent.ACTION_POINTER_UP:
setState(STATE_NON);
break;
}
return super.onTouchEvent(event);
}
/**
* set maximum zooming scale
* @param maxScale
*/
public void setMaxScale(final float maxScale) {
if ((mMinScale > maxScale) || (maxScale <= 0)) return;
if (mMaxScale != maxScale) {
mMaxScale = maxScale;
checkScale();
}
}
/**
* set minimum zooming scale
* @param minScale
*/
public void setMinScale(final float minScale) {
if ((mMaxScale < minScale) || (minScale <= 0)) return;
if (mMinScale != minScale) {
mMinScale = minScale;
checkScale();
}
}
/**
* whether ImageView has image
* @return true if ImageView has image, false otherwise
*/
public boolean hasImage() {
return getDrawable() != null;
}
/**
* reset the zooming/rotating;
*/
public void reset() {
init();
}
/**
* set listener on start rotating (for visual/sound feedback)
* @param listener
*/
public void setOnStartRotationListener(final OnStartRotationListener listener) {
mOnStartRotationListener = listener;
}
/**
* return current listener
* @return
*/
public OnStartRotationListener getOnStartRotationListener() {
return mOnStartRotationListener;
}
/**
* return current scale
* @return
*/
public float getScale() {
return getMatrixScale();
}
/**
* return current image translate values(offset)
* @param result
* @return
*/
public PointF getTranslate(final PointF result) {
updateMatrixCache();
if (result != null) {
result.set(mMatrixCache[Matrix.MTRANS_X], mMatrixCache[Matrix.MTRANS_Y]);
}
return result;
}
/**
* get current rotating degrees
*/
public float getRotation() {
return mCurrentDegrees;
}
/**
* get new Bitmap image that currently displayed on this view(applied zooming/moving/rotating).
* @return
*/
public Bitmap getCurrentImage() {
final Bitmap offscreen = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(offscreen);
// modified to support drawables other than BitmapDrawable
canvas.setMatrix(super.getImageMatrix());
super.getDrawable().draw(canvas);
return offscreen;
}
/**
* get new partial Bitmap image from currently displayed on this view(applied zooming/moving/rotating)
* @param frame: framing rectangle that you want to cut image from the view (as view coordinates)
* @return
*/
public Bitmap getCurrentImage(final Rect frame) {
Bitmap image = getCurrentImage();
if ((frame != null) && !frame.isEmpty()) {
final Bitmap tmp = Bitmap.createBitmap(image,
frame.left, frame.top, frame.width(), frame.height(), null, false);
image.recycle();
image = tmp;
}
return image;
}
/**
* initialization of ZoomImageView called from #init
*/
private final void init() {
clearCallbacks();
if (!mIsRestored) {
// Scale the image uniformly (maintain the image's aspect ratio)
// so that both dimensions (width and height) of the image will be equal
// to or less than the corresponding dimension of the view (minus padding).
// The image is then centered in the view
// leave to super class
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
// the internal Matrix in the super class(that can get with ImageView#getImageMatrix)
// never updated when called setScaleType on current implementation.
// therefore call setFrame to update internal Matrix.
// but the behavior may change in the future implementation...
setFrame(getLeft(), getTop(), getRight(), getBottom());
// set the initial state to idle, get and save the internal Matrix.
mState = -1; setState(STATE_NON);
// get the internally calculated zooming scale to fit the view
mMinScale = getMatrixScale();
mCurrentDegrees = 0.f;
}
mIsRestored = false;
mIsRotating = Math.abs(((int)(mCurrentDegrees / 360.f)) * 360.f - mCurrentDegrees) > EPS;
// update image size
// current implementation of ImageView always hold its image as a Drawable
// (that can get ImageView#getDrawable)
// therefore update the image size from its Drawable
final Drawable dr = getDrawable();
if (dr != null) {
mImageRect.set(dr.getBounds());
} else {
mImageRect.setEmpty();
}
// set limit rectangle that the image can move
final Rect tmp = new Rect();
getDrawingRect(tmp);
mLimitRect.set(tmp);
mLimitRect.inset(MOVE_LIMIT, MOVE_LIMIT);
mLimitSegments[0] = null;
// set the scale type to ScaleType.MATRIX
super.setScaleType(ImageView.ScaleType.MATRIX);
// apply matrix
super.setImageMatrix(mImageMatrix);
}
/**
* remove all callbacks if they are in the message queue
*/
private final void clearCallbacks() {
if (mWaitImageReset != null)
removeCallbacks(mWaitImageReset);
if (mStartCheckRotate != null)
removeCallbacks(mStartCheckRotate);
if (mWaitReverseReset != null)
removeCallbacks(mWaitReverseReset);
}
/**
* check zooming scale range
*/
private final void checkScale() {
float scale = getMatrixScale();
if (scale < mMinScale) {
scale = mMinScale;
mImageMatrix.setScale(scale, scale);
mImageMatrixChanged = true;
invalidate();
} else if (scale > mMaxScale) {
scale = mMaxScale;
mImageMatrix.setScale(scale, scale);
mImageMatrixChanged = true;
invalidate();
}
}
/**
* set current state, get and save the internal Matrix int super class
* @param state: -1/STATE_NON/STATE_DRAGING/STATECHECKING
* /STATE_ZOOMING/STATE_ROTATING
*/
private final void setState(final int state) {
if (mState != state) {
mState = state;
// get and save the internal Matrix of super class
mSavedImageMatrix.set(getImageMatrix());
if (!mImageMatrix.equals(mSavedImageMatrix)) {
mImageMatrix.set(mSavedImageMatrix);
mImageMatrixChanged = true;
}
}
}
/**
* start waiting
* @param event
*/
private final void startWaiting(final MotionEvent event) {
mPrimaryId = 0;
mSecondaryId = -1;
mPrimaryX = mSecondX = event.getX();
mPrimaryY = mSecondY = event.getY();
if (mWaitImageReset == null) mWaitImageReset = new WaitImageReset();
postDelayed(mWaitImageReset, CHECK_TIMEOUT);
setState(STATE_WAITING);
}
/**
* move the image
* @param event
*/
private final boolean processDrag(final MotionEvent event) {
float dx = event.getX() - mPrimaryX;
float dy = event.getY() - mPrimaryY;
// calculate the corner coordinates of image applied matrix
// [(left,top),(right,top),(right,bottom),(left.bottom)]
mTrans[0] = mTrans[6] = mImageRect.left;
mTrans[1] = mTrans[3] = mImageRect.top;
mTrans[5] = mTrans[7] = mImageRect.bottom;
mTrans[2] = mTrans[4] = mImageRect.right;
mImageMatrix.mapPoints(mTrans);
for (int i = 0; i < 8; i += 2) {
mTrans[i] += dx;
mTrans[i+1] += dy;
}
// check whether the image can move
// if we can ignore rotating, the limit check is more easy...
boolean canMove
// check whether at lease one corner of image bounds is in the limitRect
= mLimitRect.contains(mTrans[0], mTrans[1])
|| mLimitRect.contains(mTrans[2], mTrans[3])
|| mLimitRect.contains(mTrans[4], mTrans[5])
|| mLimitRect.contains(mTrans[6], mTrans[7])
// check whether at least one corner of limitRect is in the image bounds
|| ptInPoly(mLimitRect.left, mLimitRect.top, mTrans)
|| ptInPoly(mLimitRect.right, mLimitRect.top, mTrans)
|| ptInPoly(mLimitRect.right, mLimitRect.bottom, mTrans)
|| ptInPoly(mLimitRect.left, mLimitRect.bottom, mTrans);
if (!canMove) {
// when no corner is in, we need additional check whether at least
// one side of image bounds intersect with the limit rectangle
if (mLimitSegments[0] == null) {
mLimitSegments[0] = new LineSegment(mLimitRect.left, mLimitRect.top, mLimitRect.right, mLimitRect.top);
mLimitSegments[1] = new LineSegment(mLimitRect.right, mLimitRect.top, mLimitRect.right, mLimitRect.bottom);
mLimitSegments[2] = new LineSegment(mLimitRect.right, mLimitRect.bottom, mLimitRect.left, mLimitRect.bottom);
mLimitSegments[3] = new LineSegment(mLimitRect.left, mLimitRect.bottom, mLimitRect.left, mLimitRect.top);
}
final LineSegment side = new LineSegment(mTrans[0], mTrans[1], mTrans[2], mTrans[3]);
canMove = checkIntersect(side, mLimitSegments);
if (!canMove) {
side.set(mTrans[2], mTrans[3], mTrans[4], mTrans[5]);
canMove = checkIntersect(side, mLimitSegments);
if (!canMove) {
side.set(mTrans[4], mTrans[5], mTrans[6], mTrans[7]);
canMove = checkIntersect(side, mLimitSegments);
if (!canMove) {
side.set(mTrans[6], mTrans[7], mTrans[0], mTrans[1]);
canMove = checkIntersect(side, mLimitSegments);
}
}
}
}
if (canMove) {
// TODO we need adjust dx/dy not to penetrate into the limit rectangle
// otherwise the image can not move when one side is on the border of limit rectangle.
// only calculate without rotation now because its calculation is to heavy when rotation applied.
if (!mIsRotating) {
final float left = Math.min(Math.min(mTrans[0], mTrans[2]), Math.min(mTrans[4], mTrans[6]));
final float right = Math.max(Math.max(mTrans[0], mTrans[2]), Math.max(mTrans[4], mTrans[6]));
final float top = Math.min(Math.min(mTrans[1], mTrans[3]), Math.min(mTrans[5], mTrans[7]));
final float bottom = Math.max(Math.max(mTrans[1], mTrans[3]), Math.max(mTrans[5], mTrans[7]));
if (right < mLimitRect.left) {
dx = mLimitRect.left - right;
} else if (left + EPS > mLimitRect.right) {
dx = mLimitRect.right - left - EPS;
}
if (bottom < mLimitRect.top) {
dy = mLimitRect.top - bottom;
} else if (top + EPS > mLimitRect.bottom) {
dy = mLimitRect.bottom - top - EPS;
}
}
if ((dx != 0) || (dy != 0)) {
// if (DEBUG) Log.v(TAG, String.format("processDrag:dx=%f,dy=%f", dx, dy));
// apply move
if (mImageMatrix.postTranslate(dx, dy)) {
// when image is really moved?
mImageMatrixChanged = true;
// apply to super class
super.setImageMatrix(mImageMatrix);
}
}
}
mPrimaryX = event.getX();
mPrimaryY = event.getY();
return canMove;
}
/**
* start checking whether zooming/rotating
* @param event
*/
private final void startCheck(final MotionEvent event) {
if (event.getPointerCount() > 1) {
// primary touch
mPrimaryId = event.getPointerId(0);
mPrimaryX = event.getX(0);
mPrimaryY = event.getY(0);
// secondary touch
mSecondaryId = event.getPointerId(1);
mSecondX = event.getX(1);
mSecondY = event.getY(1);
// calculate the distance between first and second touch
final float dx = mSecondX - mPrimaryX;
final float dy = mSecondY - mPrimaryY;
final float distance = (float)Math.hypot(dx, dy);
if (distance < MIN_DISTANCE) {
// ignore when the touch distance is too short
return;
}
mTouchDistance = distance;
// set pivot position to the middle coordinate
mPivotX = (mPrimaryX + mSecondX) / 2.f;
mPivotY = (mPrimaryY + mSecondY) / 2.f;
//
if (mStartCheckRotate == null)
mStartCheckRotate = new StartCheckRotate();
postDelayed(mStartCheckRotate, CHECK_TIMEOUT);
setState(STATE_CHECKING); // start zoom/rotation check
}
}
/**
* start zooming
* @param event
* @return
*/
private final void startZoom(final MotionEvent event) {
removeCallbacks(mStartCheckRotate);
setState(STATE_ZOOMING);
}
/**
* zooming
* @param event
* @return
*/
private final boolean processZoom(final MotionEvent event) {
// restore the Matrix
restoreMatrix();
// get current zooming scale
final float currentScale = getMatrixScale();
// calculate the zooming scale from the distance between touched positions
final float scale = calcScale(event);
// calculate the applied zooming scale
final float tmpScale = scale * currentScale;
if (tmpScale < mMinScale) {
// skip if the applied scale is smaller than minimum scale
return false;
} else if (tmpScale > mMaxScale) {
// skip if the applied scale is bigger than maximum scale
return false;
}
// change scale with scale value and pivot point
if (mImageMatrix.postScale(scale, scale, mPivotX, mPivotY)) {
// when Matrix is changed
mImageMatrixChanged = true;
// apply to super class
super.setImageMatrix(mImageMatrix);
}
return true;
}
/**
* calculate the zooming scale from the distance between touched position</br>
* this method ony use the index of 0 and 1 for touched position
* @param event
* @return
*/
private final float calcScale(final MotionEvent event) {
final float dx = event.getX(0) - event.getX(1);
final float dy = event.getY(0) - event.getY(1);
final float distance = (float)Math.hypot(dx, dy);
return distance / mTouchDistance;
}
/**
* check whether the touch position changed
* @param event
* @return true if the touch position changed
*/
private final boolean checkTouchMoved(final MotionEvent event) {
boolean result = true;
final int ix0 = event.findPointerIndex(mPrimaryId);
final int ix1 = event.findPointerIndex(mSecondaryId);
if (ix0 >= 0) {
// check primary touch
float x = event.getX(ix0) - mPrimaryX;
float y = event.getY(ix0) - mPrimaryY;
if (x * x + y * y < MIN_DISTANCE_SQUARE) {
// primary touch is at the almost same position
if (ix1 >= 0) {
// check secondary touch
x = event.getX(ix1) - mSecondX;
y = event.getY(ix1) - mSecondY;
if (x * x + y * y < MIN_DISTANCE_SQUARE) {
// secondary touch is also at the almost same position.
return false;
}
} else {
return false;
}
}
}
return result;
}
/**
* rotating image
* @param event
* @return