Reputation: 150739
I've fooling around with 2D graphics in the Android SDK and I'm having trouble with what should be a simple example.
I'm assuming that I'm just misunderstanding something fundamental/basic.
public class DrawView extends View {
Paint paint = new Paint();
Canvas canvas = new Canvas();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
this.canvas = canvas;
this.canvas.drawLine(0,0, 500, 500, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DrawView", "onTouchEvent: " + event.getX() + "," + event.getY() );
canvas.drawLine(0,500, 500, 0, paint);
return true;
}
}
The code above draws a single line from 0,0
to 500,500
when the app start. That parts works just fine.
The issue is that the second line isn't drawn on the touch event. The onTouchEvent
is definitely being called because I see the coordinates debug message in the log.
Can someone point out what silly thing I'm doing wrong?
Upvotes: 1
Views: 6243
Reputation: 3943
You can declare a bool variable in your class, so that you can pass it to your ondraw()
method that the user has touched and also pass X and Y with other float variables to ondraw()
methode !
But you have to vall invalidate in onTouchEvet()
so that the system will redraw the canvas using your new touch orders!
Upvotes: 0
Reputation: 31
Call postInvalidate() function. This function inform that view should be redrawed (event loop call onDraw() function).
Upvotes: 0
Reputation: 6052
You're supposed to call invalidate() at the end of onTouchEvent() to tell the system to update the screen. Calling invalidate() will call onDraw().
Also, what is fundamentally wrong is that you create a canvas in this class you have. That does absolutely nothing for you. The canvas to draw in is the one that you get from the onDraw() method. The call to canvas.drawLine() in onTouchevent isn't doing anything for you and shouldn't be there. That is an empty canvas and isn't the one that will get "posted."
In onTouchEvent() you should only gather the touch event data, and also do some processing on it if you need to. You shouldn't make any calls to drawing methods there. However, as I said, if you want to trigger a draw from onTouchEvent(), you call invalidate(). If you want to draw lines based on where you are touching, you will need to create class variables that are X and Y coordinates. You update these X and Y variables in onTouchEvent(), and then you use them in onDraw() to draw whatever you need based on these X and y variables.
Upvotes: 9