Canvas Drawing Tutorial
Introduction
Canvas is a powerful tool for drawing shapes, text, images, and other objects. In this tutorial, you'll learn how to use the Canvas API in Android to create stunning graphics and animations. Let's get started!
Setting up the Canvas
First, we need to set up a custom view that we can draw on. Create a new class that extends View and override the onDraw() method.
public class MyCanvasView extends View {
public MyCanvasView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Drawing code goes here
}
}
Drawing Basic Shapes
You can draw basic shapes such as lines, rectangles, and circles using the Canvas API. Here are some examples:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
// Draw a line
canvas.drawLine(50, 50, 200, 200, paint);
// Draw a rectangle
canvas.drawRect(100, 100, 300, 300, paint);
// Draw a circle
canvas.drawCircle(400, 400, 50, paint);
}
Drawing Text
Drawing text on a canvas is straightforward. You can set the text size, color, and other properties using the Paint object.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(50);
// Draw text
canvas.drawText("Hello, Canvas!", 100, 100, paint);
}
Using Bitmaps
You can also draw images using the Canvas API. Load a bitmap and draw it on the canvas using the drawBitmap() method.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
canvas.drawBitmap(bitmap, 100, 100, null);
}
Animating Graphics
Animating graphics involves updating the canvas at regular intervals. You can achieve this using a handler or a thread. Here's an example of a simple animation:
private Handler handler = new Handler();
private float x = 0;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
// Draw a moving circle
canvas.drawCircle(x, 100, 50, paint);
// Update the position
x += 5;
if (x > getWidth()) {
x = 0;
}
// Redraw the canvas
handler.postDelayed(new Runnable() {
@Override
public void run() {
invalidate();
}
}, 30);
}
Conclusion
In this tutorial, we covered the basics of canvas drawing in Android, including setting up the canvas, drawing basic shapes, text, and bitmaps, and animating graphics. With these skills, you can create complex and engaging graphics for your Android applications.