SlideShare a Scribd company logo
Chapter 20
Canvas
By
Dr. Ramkumar Lakshminarayanan
Introduction
The Android framework APIs provides a set 2D drawing APIs that allow you to
render your own custom graphics onto a canvas or to modify existing Views to customize
their look and feel. When drawing 2D graphics, you'll typically do so in one of two ways
Draw your graphics or animations into a View object from your layout or Draw your graphics
directly to a Canvas. In this unit we are going to explore about how to draw graphics directly
in to a canvas.
Canvas
Canvas is better when your application needs to regularly re-draw itself. Applications
such as video games should be drawing to the Canvas on its own. However, there's more than
one way to do this:
 In the same thread as your UI Activity, wherein you create a custom View component
in your layout, call invalidate() and then handle the onDraw() callback.
 Or, in a separate thread, wherein you manage a SurfaceView and perform draws to the
Canvas as fast as your thread is capable .
When you're writing an application in which you would like to perform specialized
drawing and/or control the animation of graphics, you should do so by drawing through a
Canvas. A Canvas works for you as a pretense, or interface, to the actual surface upon which
your graphics will be drawn — it holds all of your "draw" calls. Via the Canvas, your
drawing is actually performed upon an underlying Bitmap, which is placed into the window.
In the event that you're drawing within the onDraw() callback method, the Canvas is
provided for you and you need only place your drawing calls upon it. You can also acquire a
Canvas from SurfaceHolder.lockCanvas(), when dealing with a SurfaceView object. (Both of
these scenarios are discussed in the following sections.) However, if you need to create a new
Canvas, then you must define the Bitmap upon which drawing will actually be performed.
The Bitmap is always required for a Canvas. You can set up a new Canvas like this:
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Now your Canvas will draw onto the defined Bitmap. After drawing upon it with the
Canvas, you can then carry your Bitmap to another Canvas with one of
the Canvas.drawBitmap(Bitmap,...) methods. It's recommended that you ultimately draw your
final graphics through a Canvas offered to you by View.onDraw()
or SurfaceHolder.lockCanvas().
The Canvas class has its own set of drawing methods that you can use,
like drawBitmap(...),drawRect(...), drawText(...), and many more. Other classes that you
might use also have draw() methods. For example, you'll probably have
some Drawable objects that you want to put on the Canvas. Drawable has its
own draw() method that takes your Canvas as an argument.
Example – Canvas
In this example we shall see a very simple ways to work with Canvas API from
Android platform, apart from simply drawing a predefined pattern on screen, we are going to
see little bit of touch event handling in form of OnTouchListener() being implemented. The
application is designed is to place a little circular red color spot on screen at the position
or place where touch on screen has occurred.
Create a project with the name com.mjs.canvasanimation and use the following code
for the activity_main.xml.
Paint
The Paint class holds the style and color information about how to draw
geometries, text and bitmaps.
drawLine (float startX, float startY, float stopX, float stopY, Paint paint)
Draw a line segment with the specified start and stop x,y coordinates,
using the specified paint.
drawCircle (float cx, float cy, float radius, Paint paint)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>
Draw the specified circle using the specified paint.
package com.mjs.canvasanimation;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity implements OnTouchListener {
private float x;
private float y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyCustomPanel view = new MyCustomPanel(this);
ViewGroup.LayoutParams params =
new
ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
addContentView(view, params);
view.setOnTouchListener(this);
}
private class MyCustomPanel extends View {
public MyCustomPanel(Context context) {
super(context);
}
@Override
public void draw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(6);
canvas.drawLine(10,10,50,50,paint);
paint.setColor(Color.RED);
canvas.drawLine(50, 50, 90, 10, paint);
canvas.drawCircle(50, 50, 3, paint);
canvas.drawCircle(x,y,3,paint);
}
}
public boolean onTouch(View v, MotionEvent event) {
x = event.getX();
y = event.getY();
v.invalidate();
return true;
}
}
In the above activity code, we have used canvas to draw a V type shape
with two arms of different colors. When any portion of the screen is touched,
then onTouch method will be executed. This overridden method captured x and
y position of the touch point on screen, and invalidate method is going to re-
draw the view, thus showing a red filled circle at the location marked by x and y
values.
Summary
In this unit we have seen the usage of canvas in Android. Canvas, is
better when your application needs to regularly re-draw itself. Applications such
as video games should be drawing to the Canvas on its own.

More Related Content

What's hot

Image processing sw & hw
Image processing sw & hwImage processing sw & hw
Image processing sw & hw
amalalhait
 
Feature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performanceFeature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performance
Venkat Projects
 
Digital image processing
Digital image processingDigital image processing
Digital image processing
Chetan Hulsure
 
Image feature extraction
Image feature extractionImage feature extraction
Image feature extraction
Rishabh shah
 
Dip review
Dip reviewDip review
Dip review
Harish Reddy
 
Lect 06
Lect 06 Lect 06
Lect 06
Moe Moe Myint
 
Image enhancement
Image enhancementImage enhancement
Image enhancement
Kuppusamy P
 
1.arithmetic & logical operations
1.arithmetic & logical operations1.arithmetic & logical operations
1.arithmetic & logical operations
mukesh bhardwaj
 
Image Enhancement using Frequency Domain Filters
Image Enhancement using Frequency Domain FiltersImage Enhancement using Frequency Domain Filters
Image Enhancement using Frequency Domain Filters
Karthika Ramachandran
 
Introduction to digital image processing
Introduction to digital image processingIntroduction to digital image processing
Introduction to digital image processing
Hossain Md Shakhawat
 
Ray tracing
 Ray tracing Ray tracing
Ray tracing
Linh Nguyen
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
zukun
 
Homomorphic filtering
Homomorphic filteringHomomorphic filtering
Homomorphic filtering
Pramod Rathore
 
Attn-gan : fine-grained text to image generation
Attn-gan :  fine-grained text to image generationAttn-gan :  fine-grained text to image generation
Attn-gan : fine-grained text to image generation
KyuYeolJung
 
Introduction to DIGITAL IMAGE PROCESSING - DAY 1
Introduction to DIGITAL IMAGE PROCESSING - DAY 1Introduction to DIGITAL IMAGE PROCESSING - DAY 1
Introduction to DIGITAL IMAGE PROCESSING - DAY 1
vijayanand Kandaswamy
 
Lecture 15 image morphology examples
Lecture 15 image morphology examplesLecture 15 image morphology examples
Lecture 15 image morphology examples
Marwa Ahmeid
 
Application of image processing
Application of image processingApplication of image processing
Application of image processing
University of Potsdam
 
Line detection algorithms
Line detection algorithmsLine detection algorithms
Line detection algorithms
Supun Kandaudahewa, MIEEE
 
Color image processing Presentation
Color image processing PresentationColor image processing Presentation
Color image processing Presentation
Revanth Chimmani
 
Image Texture Analysis
Image Texture AnalysisImage Texture Analysis
Image Texture Analysis
lalitxp
 

What's hot (20)

Image processing sw & hw
Image processing sw & hwImage processing sw & hw
Image processing sw & hw
 
Feature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performanceFeature extraction for classifying students based on theirac ademic performance
Feature extraction for classifying students based on theirac ademic performance
 
Digital image processing
Digital image processingDigital image processing
Digital image processing
 
Image feature extraction
Image feature extractionImage feature extraction
Image feature extraction
 
Dip review
Dip reviewDip review
Dip review
 
Lect 06
Lect 06 Lect 06
Lect 06
 
Image enhancement
Image enhancementImage enhancement
Image enhancement
 
1.arithmetic & logical operations
1.arithmetic & logical operations1.arithmetic & logical operations
1.arithmetic & logical operations
 
Image Enhancement using Frequency Domain Filters
Image Enhancement using Frequency Domain FiltersImage Enhancement using Frequency Domain Filters
Image Enhancement using Frequency Domain Filters
 
Introduction to digital image processing
Introduction to digital image processingIntroduction to digital image processing
Introduction to digital image processing
 
Ray tracing
 Ray tracing Ray tracing
Ray tracing
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
 
Homomorphic filtering
Homomorphic filteringHomomorphic filtering
Homomorphic filtering
 
Attn-gan : fine-grained text to image generation
Attn-gan :  fine-grained text to image generationAttn-gan :  fine-grained text to image generation
Attn-gan : fine-grained text to image generation
 
Introduction to DIGITAL IMAGE PROCESSING - DAY 1
Introduction to DIGITAL IMAGE PROCESSING - DAY 1Introduction to DIGITAL IMAGE PROCESSING - DAY 1
Introduction to DIGITAL IMAGE PROCESSING - DAY 1
 
Lecture 15 image morphology examples
Lecture 15 image morphology examplesLecture 15 image morphology examples
Lecture 15 image morphology examples
 
Application of image processing
Application of image processingApplication of image processing
Application of image processing
 
Line detection algorithms
Line detection algorithmsLine detection algorithms
Line detection algorithms
 
Color image processing Presentation
Color image processing PresentationColor image processing Presentation
Color image processing Presentation
 
Image Texture Analysis
Image Texture AnalysisImage Texture Analysis
Image Texture Analysis
 

Similar to Android canvas-chapter20

Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
Henry Osborne
 
Plunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s beginPlunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s begin
Azilen Technologies Pvt. Ltd.
 
3.2 ws WMS.pdf
3.2 ws WMS.pdf3.2 ws WMS.pdf
3.2 ws WMS.pdf
AbhishekGorshi
 
Session8 J2ME Low Level User Interface
Session8 J2ME Low Level User InterfaceSession8 J2ME Low Level User Interface
Session8 J2ME Low Level User Interface
muthusvm
 
Canvas in html5
Canvas in html5Canvas in html5
Canvas in html5
TheCreativedev Blog
 
U5 JAVA.pptx
U5 JAVA.pptxU5 JAVA.pptx
U5 JAVA.pptx
madan r
 
Scmad Chapter06
Scmad Chapter06Scmad Chapter06
Scmad Chapter06
Marcel Caraciolo
 
An Introduction to Computer Science with Java .docx
An Introduction to  Computer Science with Java .docxAn Introduction to  Computer Science with Java .docx
An Introduction to Computer Science with Java .docx
daniahendric
 
HTML CANVAS
HTML CANVASHTML CANVAS
HTML CANVAS
Light Salt
 
Android Wear Essentials
Android Wear EssentialsAndroid Wear Essentials
Android Wear Essentials
Nilhcem
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
Mindy McAdams
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVD
Framgia Vietnam
 
canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
RutujRunwal1
 
2.1 graphics window
2.1   graphics window2.1   graphics window
2.1 graphics window
allenbailey
 
On the tomcat drive in folder cosc210 you will find file named Paint.docx
On the tomcat drive in folder cosc210 you will find file named Paint.docxOn the tomcat drive in folder cosc210 you will find file named Paint.docx
On the tomcat drive in folder cosc210 you will find file named Paint.docx
dunhamadell
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
Shraddha
 
MIDP: Game API
MIDP: Game APIMIDP: Game API
MIDP: Game API
Jussi Pohjolainen
 
HTML 5 Canvas & SVG
HTML 5 Canvas & SVGHTML 5 Canvas & SVG
HTML 5 Canvas & SVG
Ofir's Fridman
 
HTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxHTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptx
AhmadAbba6
 
Digital doodle 2perpage
Digital doodle 2perpageDigital doodle 2perpage
Digital doodle 2perpage
Silvio Cazella
 

Similar to Android canvas-chapter20 (20)

Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
Plunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s beginPlunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s begin
 
3.2 ws WMS.pdf
3.2 ws WMS.pdf3.2 ws WMS.pdf
3.2 ws WMS.pdf
 
Session8 J2ME Low Level User Interface
Session8 J2ME Low Level User InterfaceSession8 J2ME Low Level User Interface
Session8 J2ME Low Level User Interface
 
Canvas in html5
Canvas in html5Canvas in html5
Canvas in html5
 
U5 JAVA.pptx
U5 JAVA.pptxU5 JAVA.pptx
U5 JAVA.pptx
 
Scmad Chapter06
Scmad Chapter06Scmad Chapter06
Scmad Chapter06
 
An Introduction to Computer Science with Java .docx
An Introduction to  Computer Science with Java .docxAn Introduction to  Computer Science with Java .docx
An Introduction to Computer Science with Java .docx
 
HTML CANVAS
HTML CANVASHTML CANVAS
HTML CANVAS
 
Android Wear Essentials
Android Wear EssentialsAndroid Wear Essentials
Android Wear Essentials
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVD
 
canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
 
2.1 graphics window
2.1   graphics window2.1   graphics window
2.1 graphics window
 
On the tomcat drive in folder cosc210 you will find file named Paint.docx
On the tomcat drive in folder cosc210 you will find file named Paint.docxOn the tomcat drive in folder cosc210 you will find file named Paint.docx
On the tomcat drive in folder cosc210 you will find file named Paint.docx
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
 
MIDP: Game API
MIDP: Game APIMIDP: Game API
MIDP: Game API
 
HTML 5 Canvas & SVG
HTML 5 Canvas & SVGHTML 5 Canvas & SVG
HTML 5 Canvas & SVG
 
HTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxHTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptx
 
Digital doodle 2perpage
Digital doodle 2perpageDigital doodle 2perpage
Digital doodle 2perpage
 

More from Dr. Ramkumar Lakshminarayanan

IT security awareness
IT security awarenessIT security awareness
IT security awareness
Dr. Ramkumar Lakshminarayanan
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
Dr. Ramkumar Lakshminarayanan
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
Dr. Ramkumar Lakshminarayanan
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
Dr. Ramkumar Lakshminarayanan
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
Dr. Ramkumar Lakshminarayanan
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
Dr. Ramkumar Lakshminarayanan
 
Web technology today
Web technology todayWeb technology today
Web technology today
Dr. Ramkumar Lakshminarayanan
 
Php Tutorial
Php TutorialPhp Tutorial
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
Dr. Ramkumar Lakshminarayanan
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
Dr. Ramkumar Lakshminarayanan
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 

More from Dr. Ramkumar Lakshminarayanan (20)

IT security awareness
IT security awarenessIT security awareness
IT security awareness
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Web technology today
Web technology todayWeb technology today
Web technology today
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 

Android canvas-chapter20

  • 1. Chapter 20 Canvas By Dr. Ramkumar Lakshminarayanan Introduction The Android framework APIs provides a set 2D drawing APIs that allow you to render your own custom graphics onto a canvas or to modify existing Views to customize their look and feel. When drawing 2D graphics, you'll typically do so in one of two ways Draw your graphics or animations into a View object from your layout or Draw your graphics directly to a Canvas. In this unit we are going to explore about how to draw graphics directly in to a canvas. Canvas Canvas is better when your application needs to regularly re-draw itself. Applications such as video games should be drawing to the Canvas on its own. However, there's more than one way to do this:  In the same thread as your UI Activity, wherein you create a custom View component in your layout, call invalidate() and then handle the onDraw() callback.  Or, in a separate thread, wherein you manage a SurfaceView and perform draws to the Canvas as fast as your thread is capable . When you're writing an application in which you would like to perform specialized drawing and/or control the animation of graphics, you should do so by drawing through a Canvas. A Canvas works for you as a pretense, or interface, to the actual surface upon which your graphics will be drawn — it holds all of your "draw" calls. Via the Canvas, your drawing is actually performed upon an underlying Bitmap, which is placed into the window. In the event that you're drawing within the onDraw() callback method, the Canvas is provided for you and you need only place your drawing calls upon it. You can also acquire a Canvas from SurfaceHolder.lockCanvas(), when dealing with a SurfaceView object. (Both of these scenarios are discussed in the following sections.) However, if you need to create a new Canvas, then you must define the Bitmap upon which drawing will actually be performed. The Bitmap is always required for a Canvas. You can set up a new Canvas like this: Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b);
  • 2. Now your Canvas will draw onto the defined Bitmap. After drawing upon it with the Canvas, you can then carry your Bitmap to another Canvas with one of the Canvas.drawBitmap(Bitmap,...) methods. It's recommended that you ultimately draw your final graphics through a Canvas offered to you by View.onDraw() or SurfaceHolder.lockCanvas(). The Canvas class has its own set of drawing methods that you can use, like drawBitmap(...),drawRect(...), drawText(...), and many more. Other classes that you might use also have draw() methods. For example, you'll probably have some Drawable objects that you want to put on the Canvas. Drawable has its own draw() method that takes your Canvas as an argument. Example – Canvas In this example we shall see a very simple ways to work with Canvas API from Android platform, apart from simply drawing a predefined pattern on screen, we are going to see little bit of touch event handling in form of OnTouchListener() being implemented. The application is designed is to place a little circular red color spot on screen at the position or place where touch on screen has occurred. Create a project with the name com.mjs.canvasanimation and use the following code for the activity_main.xml. Paint The Paint class holds the style and color information about how to draw geometries, text and bitmaps. drawLine (float startX, float startY, float stopX, float stopY, Paint paint) Draw a line segment with the specified start and stop x,y coordinates, using the specified paint. drawCircle (float cx, float cy, float radius, Paint paint) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout>
  • 3. Draw the specified circle using the specified paint. package com.mjs.canvasanimation; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; public class MainActivity extends Activity implements OnTouchListener { private float x; private float y; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyCustomPanel view = new MyCustomPanel(this); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); addContentView(view, params); view.setOnTouchListener(this); } private class MyCustomPanel extends View { public MyCustomPanel(Context context) { super(context); } @Override public void draw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.GREEN); paint.setStrokeWidth(6); canvas.drawLine(10,10,50,50,paint); paint.setColor(Color.RED); canvas.drawLine(50, 50, 90, 10, paint); canvas.drawCircle(50, 50, 3, paint); canvas.drawCircle(x,y,3,paint); } } public boolean onTouch(View v, MotionEvent event) { x = event.getX(); y = event.getY(); v.invalidate(); return true; } }
  • 4. In the above activity code, we have used canvas to draw a V type shape with two arms of different colors. When any portion of the screen is touched, then onTouch method will be executed. This overridden method captured x and y position of the touch point on screen, and invalidate method is going to re- draw the view, thus showing a red filled circle at the location marked by x and y values. Summary In this unit we have seen the usage of canvas in Android. Canvas, is better when your application needs to regularly re-draw itself. Applications such as video games should be drawing to the Canvas on its own.