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.
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:android="http://schemas.android.com/apk/res/android"
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:
Similar Reads
How to Use Animated GIF in Android App?
In this article, we are going to show an animated gif in our project using a library. There are many methods to show a gif. We can also show a gif using WebView. Here we are going to use this library to show the gif. So here we are going to learn how to implement that feature. A sample GIF is given
3 min read
How to Add Uber Car Animation in Android App?
Google Map is being used in a lot of applications these days. Many apps need google maps services for multiple purposes. Example of such apps is our daily life applications like Zomato, Swiggy and amazon uses google maps for delivery purposes while apps like uber and ola use maps for tracking the re
7 min read
How to Make a Joke App in Android Using API Call?
Jokes are the best way to keep the face smiling. With the power of technology, we can create apps that provide instant access to a broad Category(i.e. animal, money, career, dev etc ) of jokes at any time. In this article, we will create a Joke App in Android that uses API calls to fetch jokes from
7 min read
How to Use Game Mode API in Android 13?
It has been a really long time since Android has a dedicated game mode of its own, but it appears that Google has finally listened to all the gamers out there. When the user chooses the appropriate game mode, the Game Mode API enables you to optimize your game for the greatest performance or the lon
4 min read
Canvas API in Android Jetpack Compose
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will
4 min read
How to Add Memes Using API Call in Android?
Application Programming Interface calling is the process of making requests to external web-based services to retrieve or manipulate data. APIs provide a standardized way for different software applications to communicate with each other. It involves sending a request from one application to another
4 min read
How to Create Bitmap From View in Android?
In Android, a Bitmap is a representation of an image that consists of pixels with a specified width, height, and color format. A Bitmap from a View is a Bitmap that is created from a View in your Android application. The process of creating a Bitmap from a View involves drawing the View on a Canvas
4 min read
How to Draw Over Other Apps in Android?
Sometimes we require our app to show some content on the main screen irrespective of the app running in the foreground, this process is known as drawing over other apps. There are many apps that use this functionality to provide maximum features with minimum screen coverage. This also enables the us
6 min read
How To Run Android Apps On Linux
There are many users who use Android as their portable device but they prefer working on a Linux machine. Now, there are ways or apps available that can easily sync these two platforms. But what if anyone wants to run an Android app on a Linux desktop? There are multiple uses wanting to use mobile-e
4 min read
How to Post Data to API using Volley in Android?
We have seen reading the data from API using Volley request with the help of GET request in Android. With the help of GET Request, we can display data from API in JSON format and use that data inside our application. In this article, we will take a look at posting our data to API using the POST requ
5 min read