SlideShare a Scribd company logo
2
Most read
4
Most read
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

PDF
Cinema 4D R20 ESSENTIALS
PDF
Plan601 e session 4 demo
PDF
Intro to inkscape
PDF
Intro to AutoCAD
PPTX
Android animations
PDF
DUSPviz Rhino 3D Workshop
PPTX
Cad ppt
PPS
2D CAD Module by gonzalochris
Cinema 4D R20 ESSENTIALS
Plan601 e session 4 demo
Intro to inkscape
Intro to AutoCAD
Android animations
DUSPviz Rhino 3D Workshop
Cad ppt
2D CAD Module by gonzalochris

What's hot (8)

PDF
Autocad commands-1
PDF
Auto cad 3d tutorial
PDF
Introduction to 3D Modelling
PDF
Mapping with Adobe CC
PPTX
Basic Android Animation
PDF
Inkscape - A brief
PDF
3 d autocad_2009
Autocad commands-1
Auto cad 3d tutorial
Introduction to 3D Modelling
Mapping with Adobe CC
Basic Android Animation
Inkscape - A brief
3 d autocad_2009
Ad

Similar to Android canvas-chapter20 (20)

PPTX
Java Assignment Sample: Building Software with Objects, Graphics, Containers,...
PPTX
Drawing with the HTML5 Canvas
PPTX
introduction of HTML canvas and styles .pptx
PDF
Plunge into HTML5 Canvas – Let’s begin
PDF
3.2 ws WMS.pdf
PPT
Session8 J2ME Low Level User Interface
PPTX
Canvas in html5
PPTX
U5 JAVA.pptx
PPT
Scmad Chapter06
DOCX
An Introduction to Computer Science with Java .docx
PPTX
HTML CANVAS
PDF
Android Wear Essentials
PPTX
Introduction to HTML5 Canvas
PPT
Canvas in html5 - TungVD
PPTX
canvas_1.pptx
PPTX
2.1 graphics window
DOCX
On the tomcat drive in folder cosc210 you will find file named Paint.docx
PPT
Java Graphics
PPT
MIDP: Game API
PPTX
HTML 5 Canvas & SVG
Java Assignment Sample: Building Software with Objects, Graphics, Containers,...
Drawing with the HTML5 Canvas
introduction of HTML canvas and styles .pptx
Plunge into HTML5 Canvas – Let’s begin
3.2 ws WMS.pdf
Session8 J2ME Low Level User Interface
Canvas in html5
U5 JAVA.pptx
Scmad Chapter06
An Introduction to Computer Science with Java .docx
HTML CANVAS
Android Wear Essentials
Introduction to HTML5 Canvas
Canvas in html5 - TungVD
canvas_1.pptx
2.1 graphics window
On the tomcat drive in folder cosc210 you will find file named Paint.docx
Java Graphics
MIDP: Game API
HTML 5 Canvas & SVG
Ad

More from Dr. Ramkumar Lakshminarayanan (20)

PPT
IT security awareness
PPT
Basics of IT security
PDF
IT Security Awareness Posters
PPT
Normalisation revision
PPTX
Windows mobile programming
PPTX
Concurrency control
PPT
Web technology today
PDF
Phonegap for Android
PDF
Create and Sell Android App (in tamil)
PDF
Android app - Creating Live Wallpaper (tamil)
PDF
Android Tips (Tamil)
PDF
Android Animation (in tamil)
PDF
Creating List in Android App (in tamil)
PDF
Single Touch event view in Android (in tamil)
PDF
Android Application using seekbar (in tamil)
PDF
Rating Bar in Android Example
PDF
Creating Image Gallery - Android app (in tamil)
PDF
Create Android App using web view (in tamil)
PDF
Hardware Interface in Android (in tamil)
IT security awareness
Basics of IT security
IT Security Awareness Posters
Normalisation revision
Windows mobile programming
Concurrency control
Web technology today
Phonegap for Android
Create and Sell Android App (in tamil)
Android app - Creating Live Wallpaper (tamil)
Android Tips (Tamil)
Android Animation (in tamil)
Creating List in Android App (in tamil)
Single Touch event view in Android (in tamil)
Android Application using seekbar (in tamil)
Rating Bar in Android Example
Creating Image Gallery - Android app (in tamil)
Create Android App using web view (in tamil)
Hardware Interface in Android (in tamil)

Recently uploaded (6)

PDF
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
PPTX
ASMS Telecommunication company Profile
DOC
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
DOC
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
PDF
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
PDF
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
ASMS Telecommunication company Profile
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf

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.