11package com .vogella .android .customview .canvas ;
22
33import java .util .ArrayList ;
4+ import java .util .Iterator ;
45import java .util .List ;
56import java .util .Random ;
67
@@ -21,7 +22,6 @@ public class DrawingView extends View {
2122 /** Need to track this so the dirty region can accommodate the stroke. **/
2223 private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2 ;
2324
24- private Paint paint = new Paint ();
2525 private List <Path > paths = new ArrayList <Path >();
2626 private List <Paint > paints = new ArrayList <Paint >();
2727
@@ -34,7 +34,7 @@ public class DrawingView extends View {
3434
3535 private int [] colors ;
3636
37- private Path path ;
37+ private Path path = new Path () ;
3838
3939 private int nextColor ;
4040
@@ -45,13 +45,19 @@ public DrawingView(Context context, AttributeSet attrs) {
4545
4646 colors = new int [] { Color .BLUE , Color .CYAN , Color .GREEN ,
4747 Color .MAGENTA , Color .YELLOW , Color .RED , Color .WHITE };
48+
4849 random = new Random ();
4950 nextColor = random .nextInt (colors .length );
50- paint .setAntiAlias (true );
51- paint .setColor (Color .WHITE );
52- paint .setStyle (Paint .Style .STROKE );
53- paint .setStrokeJoin (Paint .Join .ROUND );
54- paint .setStrokeWidth (STROKE_WIDTH );
51+ for (int i = 0 ; i < colors .length ; i ++) {
52+ Paint paint = new Paint ();
53+ paint .setAntiAlias (true );
54+ paint .setColor (colors [i ]);
55+ paint .setStyle (Paint .Style .STROKE );
56+ paint .setStrokeJoin (Paint .Join .ROUND );
57+ paint .setStrokeWidth (STROKE_WIDTH );
58+ paints .add (paint );
59+ }
60+
5561 }
5662
5763 /**
@@ -67,10 +73,16 @@ public void clear() {
6773
6874 @ Override
6975 protected void onDraw (Canvas canvas ) {
70- canvas .drawARGB (50 , 255 , 0 , 0 );
76+ if (isInEditMode ()) {
77+ canvas .drawARGB (255 , 255 , 0 , 0 );
78+ }
79+ super .onDraw (canvas );
7180 int i = 0 ;
7281 for (Path path : paths ) {
7382 canvas .drawPath (path , paints .get (i ++));
83+ if (i == paints .size ()) {
84+ i = 0 ;
85+ }
7486 }
7587 }
7688
@@ -81,16 +93,15 @@ public boolean onTouchEvent(MotionEvent event) {
8193
8294 switch (event .getAction ()) {
8395 case MotionEvent .ACTION_DOWN :
96+ path = new Path ();
97+ paths .add (path );
8498 path .moveTo (eventX , eventY );
8599 return true ;
86100
87101 case MotionEvent .ACTION_MOVE :
102+ path .lineTo (eventX , eventY );
88103 case MotionEvent .ACTION_UP :
89-
90- path .lineTo (x , y );
91-
92104 // After replaying history, connect the line to the touch point.
93- path .lineTo (eventX , eventY );
94105 break ;
95106
96107 default :
0 commit comments