Problem: Canvas onDraw Android

  • Replies:0
Pancake
  • Forum posts: 1

Dec 19, 2013, 5:25:18 PM via Website

Hello!

I have been trying to draw different rectangles on the canvas after several times of button click. It should display different colored rectangle and the rectangle should remain on canvas after every button click. The rectangles should be able to move around the canvas.

I have 4 buttons on my main.xml file.

After invoking the first button, a blue colored rectangle shld appear on the canvas. If the first button is invoked the second time, another blue colored rectangle shld appear as well however the code i have right now only appear one blue rectangle regardless the number of times the button is invoked.

Here are my codes:

1public class DrawRectangle extends View {
2
3public DrawRectangle(Context context){
4
5 super(context);
6
7}
8
9protected void onDraw(Canvas canvas) {
10 // TODO Auto-generated method stub
11 super.onDraw(canvas);
12
13 Rect ourRect = new Rect();
14
15 ourRect.set(0, 0, canvas.getWidth()/4, canvas.getHeight()/4);
16
17 Paint paintColor = new Paint();
18
19 // make the entire canvas white
20 paintColor.setColor(Color.WHITE);
21 canvas.drawPaint(paintColor);
22
23
24
25 if(MainActivity.isBlue){
26 paintColor.setColor(Color.BLUE);
27 }
28
29 paintColor.setStyle(Paint.Style.FILL);
30
31 //Draw to actual canvas
32 canvas.drawRect(ourRect, paintColor);
33 canvas.save();
34
35 if(MainActivity.isRed){
36 paintColor.setColor(Color.RED);
37 }
38
39 paintColor.setStyle(Paint.Style.FILL);
40
41 //Draw to actual canvas
42 canvas.drawRect(ourRect, paintColor);
43 canvas.save();
44
45 if(MainActivity.isYellow){
46 paintColor.setColor(Color.YELLOW);
47 }
48
49 paintColor.setStyle(Paint.Style.FILL);
50 canvas.save();
51
52 //Draw to actual canvas
53 canvas.drawRect(ourRect, paintColor);
54
55 if(MainActivity.isGreen){
56 paintColor.setColor(Color.GREEN);
57 }
58
59 paintColor.setStyle(Paint.Style.FILL);
60
61 //Draw to actual canvas
62 canvas.drawRect(ourRect, paintColor);
63 canvas.save();
64
65
66 }
67
68 }

ans this is my code for my first button:
1public static boolean isBlue, isRed, isYellow, isGreen;
2DrawRectangle dv;
3
4bluebutton.setOnClickListener(new View.OnClickListener() {
5
6 @Override
7 public void onClick(View arg0) {
8
9 // TODO Auto-generated method stub
10 isBlue = true;
11 isRed = false;
12 isGreen = false;
13 isYellow = false;
14
15
16 dv.invalidate();
17
18 }
19
20 });


Please advice. Thank you.

— modified on Dec 19, 2013, 5:26:43 PM

Reply