-
Notifications
You must be signed in to change notification settings - Fork 179
/
PieChartRender.java
1131 lines (989 loc) · 43.3 KB
/
PieChartRender.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.razerdp.widget.animatedpieview.render;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.annotation.FloatRange;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import com.razerdp.widget.animatedpieview.AnimatedPieViewConfig;
import com.razerdp.widget.animatedpieview.BasePieLegendsView;
import com.razerdp.widget.animatedpieview.DefaultPieLegendsView;
import com.razerdp.widget.animatedpieview.IPieView;
import com.razerdp.widget.animatedpieview.callback.OnPieLegendBindListener;
import com.razerdp.widget.animatedpieview.data.IPieInfo;
import com.razerdp.widget.animatedpieview.data.PieOption;
import com.razerdp.widget.animatedpieview.utils.AnimationCallbackUtils;
import com.razerdp.widget.animatedpieview.utils.PLog;
import com.razerdp.widget.animatedpieview.utils.Util;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by 大灯泡 on 2018/2/1.
*/
public class PieChartRender extends BaseRender implements ITouchRender {
enum DrawMode {
DRAW,
TOUCH
}
enum LineDirection {
TOP_RIGHT(1, 0),
BOTTOM_RIGHT(1, 1),
TOP_LEFT(0, 0),
BOTTOM_LEFT(0, 1),
CENTER_RIGHT(1, -1),
CENTER_LEFT(0, -1);
int xDirection;//0:left 1:right
int yDirection;//-1:center 0:top 1:bottom
LineDirection(int xDirection, int yDirection) {
this.xDirection = xDirection;
this.yDirection = yDirection;
}
}
private List<PieInfoWrapper> mDataWrappers;
private List<PieInfoWrapper> mCachedDrawWrappers;
private PathMeasure mPathMeasure;
private AnimatedPieViewConfig mConfig;
private DrawMode mDrawMode = DrawMode.DRAW;
//-----------------------------------------draw area-----------------------------------------
private RectF pieBounds;
private float pieRadius;
private int maxDescTextLength;
private volatile boolean isInAnimating;
//-----------------------------------------anim area-----------------------------------------
private PieInfoWrapper mDrawingPie;
private float animAngle;
//-----------------------------------------other-----------------------------------------
private TouchHelper mTouchHelper;
private LegendsHelper mLegendsHelper;
private RenderAnimation mRenderAnimation;
private volatile boolean animHasStart;
private volatile boolean hasRenderDefaultSelected;
public PieChartRender(IPieView iPieView) {
super(iPieView);
mDataWrappers = new ArrayList<>();
mCachedDrawWrappers = new ArrayList<>();
mPathMeasure = new PathMeasure();
pieBounds = new RectF();
mTouchHelper = new TouchHelper();
mLegendsHelper = new LegendsHelper();
pieRadius = 0;
}
@Override
public void reset() {
mTouchHelper.reset();
mLegendsHelper.reset();
pieBounds.setEmpty();
animHasStart = false;
isInAnimating = false;
pieRadius = 0;
hasRenderDefaultSelected = false;
mDataWrappers = mDataWrappers == null ? new ArrayList<PieInfoWrapper>() : mDataWrappers;
mDataWrappers.clear();
mCachedDrawWrappers = mCachedDrawWrappers == null ? new ArrayList<PieInfoWrapper>() : mCachedDrawWrappers;
mCachedDrawWrappers.clear();
mDrawingPie = null;
mRenderAnimation = null;
mIPieView.getPieView().clearAnimation();
}
@Override
public boolean onPrepare() {
mConfig = mIPieView.getConfig();
if (mConfig == null) {
Log.e(TAG, "onPrepare: config is null,abort draw because of preparing failed");
return false;
}
setDrawMode(DrawMode.DRAW);
mTouchHelper.prepare();
prepareAnim();
//wrap datas and calculate sum value
//包裹数据并且计算总和
double sum = 0;
PieInfoWrapper preWrapper = null;
for (Pair<IPieInfo, Boolean> info : mConfig.getDatas()) {
sum += Math.abs(info.first.getValue());
PieInfoWrapper wrapper = new PieInfoWrapper(info.first);
wrapper.setAutoDesc(info.second);
//简单的形成一个链表
if (preWrapper != null) {
preWrapper.setNextWrapper(wrapper);
wrapper.setPreWrapper(preWrapper);
}
preWrapper = wrapper;
mDataWrappers.add(wrapper);
}
//图例
final boolean withLegends = mConfig.getLegendsParent() != null;
//calculate degree for each pieInfoWrapper
//计算每个wrapper的角度
float lastAngle = mConfig.getStartAngle();
int position = 0;
for (PieInfoWrapper dataWrapper : mDataWrappers) {
dataWrapper.prepare(mConfig);
lastAngle = dataWrapper.calculateDegree(lastAngle, sum, mConfig);
int textWidth = mPieManager.measureTextBounds(dataWrapper.getDesc(), (int) mConfig.getTextSize())
.width();
int textHeight = mPieManager.measureTextBounds(dataWrapper.getDesc(), (int) mConfig.getTextSize())
.height();
int labelWidth = 0;
int labelHeight = 0;
int labelPadding = 0;
Bitmap label = dataWrapper.getIcon(textWidth, textHeight);
if (label != null) {
if (dataWrapper.getPieOption() != null) {
labelPadding = dataWrapper.getPieOption().getLabelPadding();
}
labelWidth = label.getWidth();
labelHeight = label.getHeight();
}
textWidth += labelWidth + labelPadding * 2;
maxDescTextLength = Math.max(maxDescTextLength, textWidth);
PLog.i("desc >> " + dataWrapper.getDesc() + " maxDesTextSize >> " + maxDescTextLength);
if (withLegends) {
mLegendsHelper.put(dataWrapper.getId(), getLegendsView(mConfig, position, dataWrapper
.getPieInfo()));
}
position++;
}
if (withLegends) {
mLegendsHelper.prepare();
}
return true;
}
private BasePieLegendsView getLegendsView(AnimatedPieViewConfig config, int position, IPieInfo pieInfo) {
OnPieLegendBindListener legendBindListener = config.getPieLegendListener();
BasePieLegendsView result = null;
if (legendBindListener != null) {
result = legendBindListener.onCreateLegendView(position, pieInfo);
}
if (result == null) {
result = DefaultPieLegendsView.newInstance(mIPieView.getViewContext());
}
return result;
}
private void prepareAnim() {
if (mConfig.isAnimatePie()) {
mRenderAnimation = new RenderAnimation();
mRenderAnimation.setInterpolator(mConfig.getAnimationInterpolator());
mRenderAnimation.setDuration(mConfig.getDuration());
mRenderAnimation.setAnimationListener(new AnimationCallbackUtils.SimpleAnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
super.onAnimationStart(animation);
isInAnimating = true;
}
@Override
public void onAnimationEnd(Animation animation) {
isInAnimating = false;
onDrawFinish();
}
});
}
}
@Override
public void onSizeChanged(int width, int height, int paddingLeft, int paddingTop, int paddingRight, int paddingBottom) {
if (mTouchHelper != null) {
mTouchHelper.setCenter();
}
}
//-----------------------------------------render draw-----------------------------------------
@Override
public void onDraw(Canvas canvas) {
float width = mPieManager.getDrawWidth();
float height = mPieManager.getDrawHeight();
float centerX = width / 2;
float centerY = height / 2;
canvas.translate(centerX, centerY);
measurePieRadius(width, height);
switch (mDrawMode) {
case DRAW:
renderDraw(canvas);
break;
case TOUCH:
renderTouch(canvas);
break;
}
}
private void renderDraw(Canvas canvas) {
if (mConfig.isAnimatePie()) {
if (mRenderAnimation != null && !isInAnimating && !animHasStart) {
animHasStart = true;
mIPieView.getPieView().startAnimation(mRenderAnimation);
return;
}
renderAnimDraw(canvas);
} else {
renderNormalDraw(canvas);
}
}
private void renderTouch(Canvas canvas) {
drawCachedPie(canvas, mTouchHelper.sameClick ? mTouchHelper.lastFloatWrapper : mTouchHelper.floatingWrapper);
renderTouchDraw(canvas, mTouchHelper.lastFloatWrapper, mTouchHelper.floatDownTime);
mLegendsHelper.onPieFloatDown(mTouchHelper.lastFloatWrapper, mTouchHelper.floatDownTime);
renderTouchDraw(canvas, mTouchHelper.floatingWrapper, mTouchHelper.floatUpTime);
mLegendsHelper.onPieFloatUp(mTouchHelper.floatingWrapper, mTouchHelper.floatUpTime);
}
private void renderNormalDraw(Canvas canvas) {
if (Util.isListEmpty(mCachedDrawWrappers) || mCachedDrawWrappers.size() != mDataWrappers.size()) {
mCachedDrawWrappers.clear();
mCachedDrawWrappers.addAll(mDataWrappers);
}
drawCachedPie(canvas, null);
for (PieInfoWrapper cachedDrawWrapper : mCachedDrawWrappers) {
mLegendsHelper.onPieDrawFinish(cachedDrawWrapper);
}
onDrawFinish();
}
private void renderAnimDraw(Canvas canvas) {
if (mDrawingPie != null) {
drawCachedPie(canvas, mDrawingPie);
canvas.drawArc(pieBounds,
mDrawingPie.getFromAngle(),
animAngle - mDrawingPie.getFromAngle() - mConfig.getSplitAngle(),
!mConfig.isStrokeMode(),
mDrawingPie.getDrawPaint());
if (animAngle >= mDrawingPie.getMiddleAngle() && animAngle <= mDrawingPie.getToAngle()) {
drawText(canvas, mDrawingPie);
}
mLegendsHelper.onPieDrawing(mDrawingPie, angleToProgress(animAngle, mDrawingPie));
}
}
private void renderTouchDraw(Canvas canvas, PieInfoWrapper wrapper, float timeSet) {
if (wrapper == null) return;
mTouchHelper.setTouchBounds(timeSet);
Paint touchPaint = mTouchHelper.prepareTouchPaint(wrapper);
touchPaint.setShadowLayer(mConfig.getFloatShadowRadius() * timeSet, 0, 0, touchPaint.getColor());
touchPaint.setStrokeWidth(mConfig.getStrokeWidth() + (mConfig.getFloatExpandSize() * timeSet));
applyAlphaToPaint(wrapper, touchPaint);
canvas.drawArc(mTouchHelper.touchBounds,
wrapper.getFromAngle() - (mConfig.getFloatExpandAngle() * timeSet),
wrapper.getSweepAngle() + (mConfig.getFloatExpandAngle() * 2 * timeSet) - mConfig.getSplitAngle(),
!mConfig.isStrokeMode(),
touchPaint);
}
private void drawCachedPie(Canvas canvas, PieInfoWrapper excluded) {
if (!Util.isListEmpty(mCachedDrawWrappers)) {
for (PieInfoWrapper cachedDrawWrapper : mCachedDrawWrappers) {
drawText(canvas, cachedDrawWrapper);
Paint paint = cachedDrawWrapper.getAlphaDrawPaint();
applyAlphaToPaint(cachedDrawWrapper, paint);
if (cachedDrawWrapper.equals(excluded)) {
continue;
}
canvas.drawArc(pieBounds,
cachedDrawWrapper.getFromAngle(),
cachedDrawWrapper.getSweepAngle() - mConfig.getSplitAngle(),
!mConfig.isStrokeMode(),
paint);
}
}
}
private void drawText(Canvas canvas, PieInfoWrapper wrapper) {
if (wrapper == null) return;
if (!mConfig.isDrawText()) {
if (wrapper.mTextArea != null && !wrapper.mTextArea.isEmpty()) {
wrapper.mTextArea.setEmpty();
}
return;
}
PieOption pieOption = wrapper.getPieOption();
if (wrapper.mTextArea == null) {
wrapper.mTextArea = new RectF();
}
//根据touch扩大量修正指示线和描述文字的位置
float fixPos = (wrapper.equals(mTouchHelper.floatingWrapper) ? getFixTextPos(wrapper) : 0) + (wrapper
.equals(mTouchHelper.lastFloatWrapper) ? getFixTextPos(wrapper) : 0);
final float pointMargins = fixPos
+ pieRadius
+ mConfig.getGuideLineMarginStart()
+ (mConfig.isStrokeMode() ? mConfig.getStrokeWidth() / 2 : 0);
float cx = (float) (pointMargins * Math.cos(Math.toRadians(wrapper.getMiddleAngle())));
float cy = (float) (pointMargins * Math.sin(Math.toRadians(wrapper.getMiddleAngle())));
//画点
Paint paint = wrapper.getAlphaDrawPaint();
if (angleToProgress(animAngle, wrapper) > 0.5) {
applyAlphaToPaint(wrapper, paint);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(cx, cy, mConfig.getGuidePointRadius(), paint);
}
//画线
float guideLineEndX1 = -1;
float guideLineEndY1 = -1;
float guideLineEndX2 = -1;
float guideLineEndY2 = -1;
String desc = wrapper.getDesc();
Rect textBounds = mPieManager.measureTextBounds(desc, (int) mConfig.getTextSize());
int textBoundsWidth = textBounds.width();
int textBoundsHeight = textBounds.height();
//label
Bitmap icon = wrapper.getIcon(textBoundsWidth, textBoundsHeight);
int labelWidth = 0;
int labelHeight = 0;
int labelPadding = 0;
if (icon != null) {
labelWidth = icon.getWidth();
labelHeight = icon.getHeight();
labelPadding = Math.max(0, wrapper.getPieOption() == null ? 0 : wrapper.getPieOption()
.getLabelPadding());
}
float textLength = textBoundsWidth + mConfig.getTextMargin() + 2 * labelPadding + labelWidth;
//计算拐角方向
LineDirection direction = calculateLineGravity(cx, cy);
float guideMiddleLength = Math.abs(cy / 6);
switch (direction) {
case TOP_LEFT:
guideLineEndX1 = cx - guideMiddleLength * absMathCos(-45) - fixPos;
guideLineEndY1 = cy - guideMiddleLength * absMathCos(-45) - fixPos;
guideLineEndX2 = guideLineEndX1 - textLength;
break;
case TOP_RIGHT:
guideLineEndX1 = cx + guideMiddleLength * absMathCos(45) + fixPos;
guideLineEndY1 = cy - guideMiddleLength * absMathCos(45) - fixPos;
guideLineEndX2 = guideLineEndX1 + textLength;
break;
case CENTER_LEFT:
guideLineEndX1 = cx - guideMiddleLength - fixPos;
guideLineEndY1 = cy;
guideLineEndX2 = guideLineEndX1 - textLength;
break;
case CENTER_RIGHT:
guideLineEndX1 = cx + guideMiddleLength + fixPos;
guideLineEndY1 = cy;
guideLineEndX2 = guideLineEndX1 + textLength;
break;
case BOTTOM_LEFT:
guideLineEndX1 = cx - guideMiddleLength * absMathCos(-45) - fixPos;
guideLineEndY1 = cy + guideMiddleLength * absMathCos(-45) + fixPos;
guideLineEndX2 = guideLineEndX1 - textLength;
break;
case BOTTOM_RIGHT:
guideLineEndX1 = cx + guideMiddleLength * absMathCos(45) + fixPos;
guideLineEndY1 = cy + guideMiddleLength * absMathCos(45) + fixPos;
guideLineEndX2 = guideLineEndX1 + textLength;
break;
}
guideLineEndY2 = guideLineEndY1;
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mConfig.getGuideLineWidth());
paint.setStrokeJoin(Paint.Join.ROUND);
Path path = wrapper.getLinePath();
Path measurePathDst = wrapper.getLinePathMeasure();
path.moveTo(cx, cy);
path.lineTo(guideLineEndX1, guideLineEndY1);
path.lineTo(guideLineEndX2, guideLineEndY2);
mPathMeasure.nextContour();
mPathMeasure.setPath(path, false);
float progress = angleToProgress(animAngle, wrapper);
mPathMeasure.getSegment(0, progress * mPathMeasure.getLength(), measurePathDst, true);
canvas.drawPath(measurePathDst, paint);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(mConfig.getTextSize());
paint.setAlpha((int) (255 * progress));
float textStartX = calculateTextStartX(guideLineEndX1, guideLineEndX2, direction, textBoundsWidth);
float textStartY = calculateTextStartY(guideLineEndY1, guideLineEndY2, direction, textBoundsHeight);
float textAreaLeft = direction.xDirection == 1 ? guideLineEndX1 : guideLineEndX2;
float textAreaTop = textStartY - textBoundsHeight - mConfig.getTextMargin();
float textAreaRight = direction.xDirection == 1 ? guideLineEndX2 : guideLineEndX1;
float textAreaBottom = textStartY;
if (icon != null) {
textStartX = fitTextStartXWithLabel(textStartX, textBoundsWidth, labelWidth, direction, wrapper
.getPieOption());
float iconLeft = calculateLabelX(wrapper.getPieOption(), labelWidth, textStartX, direction, textBoundsWidth);
if (Float.isNaN(iconLeft) && iconLeft <= textStartX) {
textAreaLeft = iconLeft;
}
float iconTop = textStartY - textBoundsHeight;
if (textBoundsHeight == 0) {
switch (mConfig.getTextGravity()) {
case AnimatedPieViewConfig.ABOVE:
textAreaTop = iconTop = textStartY - icon.getHeight();
break;
case AnimatedPieViewConfig.ECTOPIC:
if (direction.yDirection == 0) {
textAreaTop = iconTop = textStartY - icon.getHeight();
}
break;
case AnimatedPieViewConfig.ALIGN:
textAreaTop = iconTop = textStartY - icon.getHeight() / 2;
break;
default:
break;
}
}
if (!Float.isNaN(iconLeft)) {
canvas.drawBitmap(icon, iconLeft, iconTop, wrapper.getIconPaint());
}
}
//text area
wrapper.mTextArea.set(textAreaLeft, textAreaTop, textAreaRight, textAreaBottom);
Typeface defaultTypeFace = paint.getTypeface();
if (pieOption != null && pieOption.getTypeFace() != null) {
paint.setTypeface(pieOption.getTypeFace());
}
//画文字
canvas.drawText(desc, textStartX, textStartY, paint);
paint.setTypeface(defaultTypeFace);
}
private float fitTextStartXWithLabel(float textStartX, int textBoundsWidth, int labelWidth, LineDirection direction, PieOption pieOption) {
if (pieOption != null) {
int labelPadding = pieOption.getLabelPadding();
switch (pieOption.getLabelPosition()) {
case PieOption.NEAR_PIE:
if (direction.xDirection < 1) {
//文字在左边,图片在文字右边时,需要针对文字位置适配
textStartX -= labelPadding * 2 + labelWidth;
} else {
textStartX += labelPadding * 2 + labelWidth;
}
break;
}
}
return textStartX;
}
private float calculateLabelX(PieOption pieOption, int iconWidth, float textStartX, LineDirection direction, int textWidth) {
if (pieOption == null) return Float.NaN;
float result;
int labelPosition = pieOption.getLabelPosition();
int padding = pieOption.getLabelPadding();
switch (direction) {
case TOP_LEFT:
case CENTER_LEFT:
case BOTTOM_LEFT:
if (labelPosition == PieOption.NEAR_PIE) {
result = textStartX + textWidth + padding;
} else {
result = textStartX - iconWidth - padding;
}
break;
case TOP_RIGHT:
case CENTER_RIGHT:
case BOTTOM_RIGHT:
if (labelPosition == PieOption.NEAR_PIE) {
result = textStartX - iconWidth - padding;
} else {
result = textStartX + textWidth + padding;
}
break;
default:
return Float.NaN;
}
return result;
}
private float calculateTextStartX(float guideLineEndX1, float guideLineEndX2, LineDirection direction, int textWidth) {
final int textGravity = mConfig.getTextGravity();
final int textMargin = mConfig.getTextMargin();
switch (direction) {
case TOP_LEFT:
case CENTER_LEFT:
case BOTTOM_LEFT:
return textGravity == AnimatedPieViewConfig.ALIGN ? guideLineEndX2 - textWidth - textMargin : guideLineEndX1 - textWidth - textMargin;
case TOP_RIGHT:
case CENTER_RIGHT:
case BOTTOM_RIGHT:
return textGravity == AnimatedPieViewConfig.ALIGN ? guideLineEndX2 + textMargin : guideLineEndX1 + textMargin;
default:
return guideLineEndX1;
}
}
private float calculateTextStartY(float guideLineEndY1, float guideLineEndY2, LineDirection direction, int textHeight) {
final int textGravity = mConfig.getTextGravity();
final int textMargin = mConfig.getTextMargin();
switch (direction) {
case TOP_LEFT:
case CENTER_LEFT:
case TOP_RIGHT:
if (textGravity == AnimatedPieViewConfig.ABOVE || textGravity == AnimatedPieViewConfig.ECTOPIC) {
return guideLineEndY1 - textMargin - textHeight / 2;
} else if (textGravity == AnimatedPieViewConfig.BELOW) {
return guideLineEndY1 + textMargin + textHeight;
} else {
return guideLineEndY1 + textHeight / 2;
}
case BOTTOM_LEFT:
case CENTER_RIGHT:
case BOTTOM_RIGHT:
if (textGravity == AnimatedPieViewConfig.ABOVE) {
return guideLineEndY1 - textMargin - textHeight / 2;
} else if (textGravity == AnimatedPieViewConfig.BELOW || textGravity == AnimatedPieViewConfig.ECTOPIC) {
return guideLineEndY1 + textMargin + textHeight;
} else {
return guideLineEndY1 + textHeight / 2;
}
default:
return guideLineEndY1 - textMargin - textHeight / 2;
}
}
private LineDirection calculateLineGravity(float startX, float startY) {
if (startX > 0) {
//在右边
return startY > 0 ? LineDirection.BOTTOM_RIGHT : LineDirection.TOP_RIGHT;
} else if (startX < 0) {
//在左边
return startY > 0 ? LineDirection.BOTTOM_LEFT : LineDirection.TOP_LEFT;
} else if (startY == 0) {
//刚好中间
return startX > 0 ? LineDirection.CENTER_RIGHT : LineDirection.CENTER_LEFT;
}
return LineDirection.TOP_RIGHT;
}
private float getFixTextPos(PieInfoWrapper wrapper) {
if (wrapper == null) return 0;
final float scaleSizeInTouch = !mConfig.isStrokeMode() ? mConfig.getFloatExpandSize() : 10;
boolean up = wrapper.equals(mTouchHelper.floatingWrapper);
return up ? scaleSizeInTouch * mTouchHelper.floatUpTime : scaleSizeInTouch * mTouchHelper.floatDownTime;
}
//-----------------------------------------render draw fin-----------------------------------------
private void applyAlphaToPaint(PieInfoWrapper target, Paint paint) {
if (paint == null) return;
if (mDrawMode == DrawMode.DRAW) {
paint.setAlpha(255);
return;
}
//如果点的是同一个,则需要特殊处理
boolean selected = false;
if (mTouchHelper.floatingWrapper != null) {
//针对浮起来的
selected = mTouchHelper.floatingWrapper.equals(target);
} else {
if (mTouchHelper.lastFloatWrapper != null) {
selected = mTouchHelper.lastFloatWrapper.equals(target);
}
}
final float alphaCut = 255 - mConfig.getFocusAlpha();
switch (mConfig.getFocusAlphaType()) {
case AnimatedPieViewConfig.FOCUS_WITH_ALPHA:
//选中的对象有alpha变化
boolean alphaDown = selected && mTouchHelper.floatingWrapper != null;
if (selected) {
paint.setAlpha((int) (255 - (alphaCut * (alphaDown ? mTouchHelper.floatUpTime : mTouchHelper.floatDownTime))));
} else {
paint.setAlpha(255);
}
break;
case AnimatedPieViewConfig.FOCUS_WITH_ALPHA_REV:
boolean alphaDown2 = !selected && mTouchHelper.floatingWrapper != null;
if (selected) {
paint.setAlpha(255);
} else {
paint.setAlpha((int) (255 - (alphaCut * (alphaDown2 ? mTouchHelper.floatUpTime : mTouchHelper.floatDownTime))));
}
break;
case AnimatedPieViewConfig.FOCUS_WITHOUT_ALPHA:
default:
paint.setAlpha(255);
break;
}
}
@Override
public void onDestroy() {
}
private void onDrawFinish() {
PLog.i("drawFinish");
mConfig.onFinish();
if (mConfig.isAnimatePie()) {
if (!animHasStart || isInAnimating) return;
}
if (hasRenderDefaultSelected) return;
for (PieInfoWrapper dataWrapper : mDataWrappers) {
if (dataWrapper.getPieOption() != null && dataWrapper.getPieOption()
.isDefaultSelected()) {
hasRenderDefaultSelected = true;
mTouchHelper.handleUp(dataWrapper);
break;
}
}
}
//-----------------------------------------touch-----------------------------------------
@Override
public boolean onTouchEvent(MotionEvent event) {
return mTouchHelper.handleTouch(event);
}
@Override
public void forceAbortTouch() {
}
//-----------------------------------------tools-----------------------------------------
private void setCurPie(PieInfoWrapper infoWrapper, float degree) {
if (mDrawingPie != null) {
if (degree >= infoWrapper.getFromAngle()) {
checkAndInsertPrePie(infoWrapper);
}
if (degree >= mDrawingPie.getToAngle()) {
PLog.i("setCurPie deg = " + degree + " from = " + infoWrapper.getFromAngle() + " to = " + infoWrapper
.getToAngle());
if (!mDrawingPie.isCached()) {
mCachedDrawWrappers.add(mDrawingPie);
mDrawingPie.setCached(true);
}
}
}
mDrawingPie = infoWrapper;
animAngle = degree;
callInvalidate();
}
// fix anim duration too short
private void checkAndInsertPrePie(PieInfoWrapper infoWrapper) {
if (infoWrapper == null || infoWrapper.isCheckPrePieCached()) return;
PieInfoWrapper preWrapper = infoWrapper.getPreWrapper();
PLog.i("lalalal " + infoWrapper.getId());
if (preWrapper == null) {
//first node
infoWrapper.setCheckPrePieCached(true);
return;
}
if (mCachedDrawWrappers.lastIndexOf(preWrapper) == -1) {
mCachedDrawWrappers.add(preWrapper);
preWrapper.setCached(true);
mLegendsHelper.onPieDrawFinish(preWrapper);
}
infoWrapper.setCheckPrePieCached(true);
checkAndInsertPrePie(preWrapper);
}
private void setDrawMode(DrawMode drawMode) {
if (drawMode == DrawMode.TOUCH && isInAnimating) return;
mDrawMode = drawMode;
}
private void measurePieRadius(float width, float height) {
if (pieRadius > 0) {
pieBounds.set(-pieRadius, -pieRadius, pieRadius, pieRadius);
return;
}
final float minSize = Math.min(width / 2, height / 2);
//最低0.5的最小高宽值
float minPieRadius = minSize / 4;
if (mConfig.isAutoSize()) {
//按照最大的文字测量
float radius = Float.MAX_VALUE;
while (radius > minSize) {
if (radius == Float.MAX_VALUE) {
radius = minSize
- (mConfig.isDrawText() ? maxDescTextLength : 0)
- (mConfig.isStrokeMode() ? (mConfig.getStrokeWidth() >> 1) : 0)
- mConfig.getGuideLineMarginStart();
} else {
radius -= minSize / 10;
}
}
pieRadius = Math.max(minPieRadius, radius);
} else {
//优先判定size
if (mConfig.getPieRadius() > 0) {
pieRadius = mConfig.getPieRadius();
} else if (mConfig.getPieRadiusRatio() > 0) {
pieRadius = minSize / 2 * mConfig.getPieRadiusRatio();
} else {
pieRadius = minPieRadius;
}
}
pieBounds.set(-pieRadius, -pieRadius, pieRadius, pieRadius);
}
private float absMathSin(double angdeg) {
return (float) Math.abs(Math.sin(Math.toRadians(angdeg)));
}
private float absMathCos(double angdeg) {
return (float) Math.abs(Math.cos(Math.toRadians(angdeg)));
}
private float angleToProgress(float angle, PieInfoWrapper wrapper) {
if (wrapper == null || !mConfig.isAnimatePie()) return 1f;
if (angle < wrapper.getMiddleAngle()) return 0f;
if (angle >= wrapper.getToAngle()) return 1f;
return (angle - wrapper.getMiddleAngle()) / (wrapper.getToAngle() - wrapper.getMiddleAngle());
}
//-----------------------------------------inner helper-----------------------------------------
private class RenderAnimation extends Animation {
private PieInfoWrapper lastFoundWrapper;
public RenderAnimation() {
lastFoundWrapper = null;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (mConfig == null) {
throw new NullPointerException("viewConfig为空");
}
PLog.i("interpolatedTime = " + interpolatedTime);
if (interpolatedTime >= 0.0f && interpolatedTime <= 1.0f) {
float angle = 360 * interpolatedTime + mConfig.getStartAngle();
PieInfoWrapper info = findPieinfoWithAngle(angle);
setCurPie(info == null ? lastFoundWrapper : info, angle);
}
}
public PieInfoWrapper findPieinfoWithAngle(float angle) {
if (Util.isListEmpty(mDataWrappers)) return null;
if (lastFoundWrapper != null && lastFoundWrapper.contains(angle)) {
return lastFoundWrapper;
}
for (PieInfoWrapper infoWrapper : mDataWrappers) {
if (infoWrapper.contains(angle)) {
lastFoundWrapper = infoWrapper;
mLegendsHelper.onPieDrawStart(lastFoundWrapper);
return infoWrapper;
}
}
return null;
}
}
private class TouchHelper {
//因为判断点击时是判断内圆和外圆半径,可能很苛刻,所以这里可以考虑增加点击范围
private int expandClickRange;
private float centerX;
private float centerY;
private RectF touchBounds;
private PieInfoWrapper floatingWrapper;
private ValueAnimator floatUpAnim;
private float floatUpTime;
private PieInfoWrapper lastFloatWrapper;
private ValueAnimator floatDownAnim;
private float floatDownTime;
private float touchX = -1;
private float touchY = -1;
private Paint mTouchPaint;
private boolean sameClick;
private PieInfoWrapper lastTouchWrapper;
TouchHelper() {
this(25);
}
TouchHelper(int expandClickRange) {
this.expandClickRange = expandClickRange;
touchBounds = new RectF();
}
void reset() {
centerX = 0;
centerY = 0;
touchBounds.setEmpty();
floatUpAnim = floatUpAnim == null ? ValueAnimator.ofFloat(0, 1) : floatUpAnim;
floatUpAnim.removeAllUpdateListeners();
floatUpTime = 0;
floatDownAnim = floatDownAnim == null ? ValueAnimator.ofFloat(0, 1) : floatDownAnim;
floatDownAnim.removeAllUpdateListeners();
floatUpTime = 0;
floatingWrapper = null;
lastFloatWrapper = null;
lastTouchWrapper = null;
touchX = -1;
touchY = -1;
sameClick = false;
}
void prepare() {
setCenter();
mTouchPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
floatUpAnim = ValueAnimator.ofFloat(0, 1);
floatUpAnim.setDuration(mConfig.getFloatUpDuration());
floatUpAnim.setInterpolator(new DecelerateInterpolator());
floatUpAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
floatUpTime = (float) animation.getAnimatedValue();
callInvalidate();
}
});
floatDownAnim = ValueAnimator.ofFloat(1, 0);
floatDownAnim.setDuration(mConfig.getFloatDownDuration());
floatDownAnim.setInterpolator(new DecelerateInterpolator());
floatDownAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
floatDownTime = (float) animation.getAnimatedValue();
callInvalidate();
}
});
}
private void setCenter() {
centerX = mPieManager.getDrawWidth() / 2;
centerY = mPieManager.getDrawHeight() / 2;
}
Paint prepareTouchPaint(PieInfoWrapper wrapper) {
if (mTouchPaint == null) {
mTouchPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
if (wrapper != null) {
mTouchPaint.set(wrapper.getDrawPaint());
}
return mTouchPaint;
}
PieInfoWrapper pointToPieInfoWrapper(float x, float y) {
final boolean isStrokeMode = mConfig.isStrokeMode();
final float strokeWidth = mConfig.getStrokeWidth();
//外圆半径
final float exCircleRadius = isStrokeMode ? pieRadius + strokeWidth / 2 : pieRadius;
//内圆半径
final float innerCircleRadius = isStrokeMode ? pieRadius - strokeWidth / 2 : 0;
//点击位置到圆心的直线距离(没开根)
final double touchDistancePow = Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2);
//内圆半径<=直线距离<=外圆半径
final boolean isTouchInRing = touchDistancePow >= expandClickRange + Math.pow(innerCircleRadius, 2)
&& touchDistancePow <= expandClickRange + Math.pow(exCircleRadius, 2);
if (!isTouchInRing) {
if (mConfig.isDrawText()) {
return findLabelTouchWrapper(x - centerX, y - centerY);
}
return null;
}
return findWrapper(x, y);
}
PieInfoWrapper findLabelTouchWrapper(float x, float y) {
if (lastTouchWrapper != null && lastTouchWrapper.containsLabelTouch(x, y)) {
return lastTouchWrapper;
}
for (PieInfoWrapper wrapper : mDataWrappers) {
if (wrapper.containsLabelTouch(x, y)) {
lastTouchWrapper = wrapper;
return wrapper;
}
}
return null;
}
PieInfoWrapper findWrapper(float x, float y) {
//得到角度
double touchAngle = Math.toDegrees(Math.atan2(y - centerY, x - centerX));
if (touchAngle < 0) {
touchAngle += 360.0f;
}
if (lastTouchWrapper != null && lastTouchWrapper.containsTouch((float) touchAngle)) {
return lastTouchWrapper;
}
PLog.i("touch角度 = " + touchAngle);
for (PieInfoWrapper wrapper : mDataWrappers) {
if (wrapper.containsTouch((float) touchAngle)) {
lastTouchWrapper = wrapper;
return wrapper;
}
}
return null;
}
void setTouchBounds(float timeSet) {
final float scaleSizeInTouch = !mConfig.isStrokeMode() ? mConfig.getFloatExpandSize() : 0;
touchBounds.set(pieBounds.left - scaleSizeInTouch * timeSet,
pieBounds.top - scaleSizeInTouch * timeSet,
pieBounds.right + scaleSizeInTouch * timeSet,
pieBounds.bottom + scaleSizeInTouch * timeSet);
}
boolean handleTouch(MotionEvent event) {
if (mConfig == null || !mConfig.isCanTouch() || isInAnimating) return false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: