Skip to content
Related Articles

Related Articles

Improve Article

How to Use Canvas API in Android Apps?

  • Last Updated : 26 Apr, 2021

Canvas API is also one of the most used in Android. The name of the API itself tells us that the API is being used for drawing on the drawing board. With the help of this API, we can draw different types of shapes and create custom UI components that are not present in Android. In this article, we will take a look at Canvas API and also use this API in our app to make a simple design. 

What is Canvas API? 

Canvas API is a drawing framework that is provided in Android, with the help of which we can create custom shapes like rectangle, circle, and many more in our UI design. With the help of this API, we can draw any type of shape for our app. The drawing of the different shapes is done using Bitmap. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Understanding the Working of Canvas API

While using this API the screen of the user’s device is called Canvas on which we have to draw different types of shapes and designs. There are different methods that are used to draw different shapes on our Canvas. Below are the methods which are used for drawing shapes on Canvas. 

Methods



Description

onMeasure()

This method is used to measure the size of the view

and the children’s present in that view. 

onDraw()

This method is use to draw the different views in our Canvas. 

With this method we can draw different shapes on our Canvas. 

There are predefined methods for different shapes such as drawRect(),

drawArc(), drawLine() and many more.

onLayout()This method helps us to set the size of the view.

Step by Step Implementation

Step 1: Create a New Project



To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idRLView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
</RelativeLayout>

Step 3: Creating a new Java class for drawing our view 

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as PaintView and add the below code to it.

Java




import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.View;
  
public class PaintView extends View {
      
    // below we are creating variables for our paint
    Paint otherPaint, outerPaint, textPaint;
     
    // and a floating variable for our left arc.
    float arcLeft;
  
    @SuppressLint("ResourceAsColor")
    public PaintView(Context context) {
        super(context);
          
        // on below line we are initializing our paint variable for our text
        textPaint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
          
        // on below line we are setting color to it.
        textPaint.setColor(Color.WHITE);
         
        // on below line we are setting text size to it.
        // In Paint we have to add text size using px so
        // we have created a method where we are converting dp to pixels.
        textPaint.setTextSize(pxFromDp(context, 24));
          
        // on below line we are initializing our outer paint
        outerPaint = new Paint();
          
        // on below line we are setting style to our paint.
        outerPaint.setStyle(Paint.Style.FILL);
          
        // on below line we are setting color to it.
        outerPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are creating a display metrics
        DisplayMetrics displayMetrics = new DisplayMetrics();
          
        // on below line we are getting display metrics.
        ((Activity) getContext()).getWindowManager()
                .getDefaultDisplay()
                .getMetrics(displayMetrics);
          
        // on below line we are assigning
        // the value to the arc left.
        arcLeft = pxFromDp(context, 20);
          
        // on below line we are creating 
        // a new variable for our paint
        otherPaint = new Paint();
    }
  
    // below method is use to generate px from DP.
    public static float pxFromDp(final Context context, final float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }
  
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
          
        // below four lines of code is use to add
        // back color to our screen which is green
        canvas.drawPaint(outerPaint);
          
        // on below line we are setting color to our paint.
        otherPaint.setColor(Color.WHITE);
          
        // on below line we are setting style to out paint.
        otherPaint.setStyle(Paint.Style.FILL);
          
        // below 4 lines of code is use to
        // create white rectangle of screen
        canvas.drawRect(
                getLeft() + (getRight() - getLeft()) / 3,
                getTop() + (getBottom() - getTop()) / 3,
                getRight() - (getRight() - getLeft()) / 3,
                getBottom() - (getBottom() - getTop()) / 3, otherPaint);
          
        // on below line we are changing the color for our paint.
        otherPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are drawing a circle and passing 
        // width, height, left arc and paint to add color.
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, arcLeft, otherPaint);
          
        // on below line we are adding text using paint in our canvas.
        canvas.drawText("Geeks for Geeks", (float) (getWidth() * 0.3), (float) (getHeight() * 0.8), textPaint);
    }
}

Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.widget.RelativeLayout;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating a variable for our relative layout
    private RelativeLayout relativeLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our view.
        relativeLayout = findViewById(R.id.idRLView);
          
        // calling our  paint view class and adding 
        // its view to our relative layout.
        PaintView paintView = new PaintView(this);
        relativeLayout.addView(paintView);
    }
}

Now run your app and see the output of the app. 

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :