Canvas In Android Example . If you want to know about Canvas In Android Example , then this article is for you. You will find a lot of information about Canvas In Android Example in this article. We hope you find the information useful and informative. You can find more articles on the website.

What is Android?

Android, the widely popular operating system, is the beating heart behind millions of smartphones and tablets globally. Developed by Google, Android is an open-source platform that powers a diverse range of devices, offering users an intuitive and customizable experience. With its user-friendly interface, Android provides easy access to a plethora of applications through the Google Play Store, catering to every need imaginable. From social media and gaming to productivity and entertainment, Android seamlessly integrates into our daily lives, ensuring that the world is at our fingertips. Whether you're a tech enthusiast or a casual user, Android's versatility and accessibility make it a cornerstone of modern mobile technology.

Canvas in Android Example: Drawing on Custom Views

Table of Contents

  1. Introduction: What is Canvas in Android?
  2. Setting Up a Custom View with Canvas
  3. Drawing Basic Shapes on Canvas
    • a. Drawing a Rectangle
    • b. Drawing a Circle
    • c. Drawing a Line
  4. Handling Touch Events with Canvas
  5. Advanced Canvas Techniques
    • a. Drawing an Image on Canvas
    • b. Applying Transformations (Scaling, Rotation)
  6. Conclusion

1. Introduction: What is Canvas in Android?

In Android, the Canvas class is part of the android.graphics package and provides a powerful set of methods to draw 2D graphics on a Bitmap or a View. Canvas is most often used in custom views, where you can override the onDraw() method to define the appearance of the view, including drawing shapes, images, and text.

Using Canvas allows developers to create interactive and dynamic custom UI elements, such as drawing apps, games, and custom charts.


2. Setting Up a Custom View with Canvas

Before drawing on a Canvas in Android, you need to create a custom view by extending the View class and overriding the onDraw() method. The onDraw() method is where the drawing happens.

Example: Basic Custom View Setup

class MyCustomView(context: Context) : View(context) {

    // Constructor
    init {
        // Initialize any properties if needed
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // Call the draw methods here
    }
}

In the above code, we have created a custom view class called MyCustomView that extends View. Inside the onDraw() method, we will perform the drawing operations.


3. Drawing Basic Shapes on Canvas

a. Drawing a Rectangle

You can draw simple shapes like rectangles using the drawRect() method of the Canvas class.

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    val paint = Paint()
    paint.color = Color.RED // Set paint color

    // Draw a rectangle with top-left corner at (50, 50) and dimensions 200x100
    canvas.drawRect(50f, 50f, 250f, 150f, paint)
}

In this example, we create a Paint object and set its color to red. Then, we use drawRect() to draw a rectangle with specific coordinates and dimensions.

b. Drawing a Circle

To draw a circle on the Canvas, you can use the drawCircle() method.

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    val paint = Paint()
    paint.color = Color.BLUE // Set paint color

    // Draw a circle with center at (200, 200) and radius 100
    canvas.drawCircle(200f, 200f, 100f, paint)
}

Here, the circle is drawn with a center at (200, 200) and a radius of 100 pixels. The paint color is set to blue.

c. Drawing a Line

You can draw a straight line on the Canvas using the drawLine() method.

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    val paint = Paint()
    paint.color = Color.GREEN // Set paint color

    // Draw a line from (50, 50) to (300, 300)
    canvas.drawLine(50f, 50f, 300f, 300f, paint)
}

This example draws a green line from the point (50, 50) to (300, 300) on the Canvas.


4. Handling Touch Events with Canvas

If you want to update the drawing based on touch events (for example, allowing users to draw on the Canvas), you can capture touch events using the onTouchEvent() method and call invalidate() to trigger a redraw.

Example: Drawing on the Canvas with Touch Events

class DrawingView(context: Context) : View(context) {

    private val path = Path()
    private val paint = Paint().apply {
        color = Color.BLACK
        style = Paint.Style.STROKE
        strokeWidth = 5f
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // Draw the path (line drawn by touch)
        canvas.drawPath(path, paint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> path.moveTo(event.x, event.y)
            MotionEvent.ACTION_MOVE -> path.lineTo(event.x, event.y)
            MotionEvent.ACTION_UP -> { /* Do nothing here */ }
        }

        // Trigger a redraw when the user is drawing
        invalidate()
        return true
    }
}

In this example, a Path is used to track the user's touch movement and draw a line on the Canvas. The onTouchEvent() method updates the path as the user touches and moves on the screen, and invalidate() ensures the view is redrawn continuously.


5. Advanced Canvas Techniques

a. Drawing an Image on Canvas

You can draw images on the Canvas by using the drawBitmap() method, which draws a Bitmap on the Canvas.

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    val bitmap = BitmapFactory.decodeResource(resources, R.drawable.my_image)

    // Draw the image at position (100, 100)
    canvas.drawBitmap(bitmap, 100f, 100f, null)
}

In this example, an image is drawn on the Canvas at the coordinates (100, 100). You need to load the Bitmap from resources using BitmapFactory.decodeResource().

b. Applying Transformations (Scaling, Rotation)

Canvas allows you to apply transformations, such as scaling and rotation, before drawing the elements. These transformations are applied globally, affecting all subsequent drawing operations.

Example: Scaling and Rotating an Image

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    val bitmap = BitmapFactory.decodeResource(resources, R.drawable.my_image)

    // Save the canvas state
    canvas.save()

    // Apply rotation and scaling
    canvas.rotate(45f, width / 2f, height / 2f) // Rotate by 45 degrees around the center
    canvas.scale(1.5f, 1.5f, width / 2f, height / 2f) // Scale by 1.5x

    // Draw the transformed image
    canvas.drawBitmap(bitmap, 100f, 100f, null)

    // Restore the canvas to its original state
    canvas.restore()
}

In this example, we apply both rotation and scaling transformations to the Canvas before drawing the image. The canvas.save() and canvas.restore() methods are used to preserve and reset the Canvas state, ensuring that the transformations don't affect other drawing operations.


6. Conclusion

The Canvas class in Android provides a versatile way to draw and manipulate graphics in custom views. By extending the View class and overriding the onDraw() method, you can create custom UI elements that respond to user input, animate, or display complex visual content.

Through the examples in this guide, you’ve learned how to:

  • Draw basic shapes like rectangles, circles, and lines.
  • Handle touch events to allow user interaction with the Canvas.
  • Apply transformations like scaling and rotation to your drawings.
  • Draw images on the Canvas.

These fundamental techniques provide a solid foundation for more advanced Canvas-based graphics, such as game development, custom animations, and interactive UI components. By mastering the use of Canvas, you can create visually rich and engaging Android applications.