How to use canvas in your android apps - Part 1


SDK Version: 
M3
If you want to use a custom layout with a canvas in your application, this tutorial may be useful to you. We will draw a kangoo at the end of this tutorial.


There is a cool article on site Custom View - HorizontalSlider, what you can use to understand the following code:

  1. [...]
  2. <com.helloandroid.canvastutorial.Panel android:id="@+id/SurfaceView01" android:layout_width="wrap_content"
  3.  
  4. android:layout_height="wrap_content" android:maxHeight="40dip">
  5. </com.helloandroid.canvastutorial.Panel>
  6. [...]

This is your main.xml.

Your main class extends Activity and similar as the following code snip:

  1. public class Canvastutorial extends Activity {
  2.     /** Called when the activity is first created. */
  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.main);
  7.     }
  8. }

Your second class called Panel.java. This class extends SurfaceView and implements SurfaceHolder.Callback. The interface requires three additional methods we need to implement: surfaceCreated(), surfaceDestroyed(), surfaceChanged().

  1. class Panel extends SurfaceView implements SurfaceHolder.Callback {
  2.     @Override
  3.     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  4.         // TODO Auto-generated method stub
  5.     }
  6.  
  7.     @Override
  8.     public void surfaceCreated(SurfaceHolder holder) {
  9.         // TODO Auto-generated method stub
  10.     }
  11.  
  12.     @Override
  13.     public void surfaceDestroyed(SurfaceHolder holder) {
  14.         // TODO Auto-generated method stub
  15.     }
  16. }

Add this constructor to code to inicialize the panel:

  1.        public Panel(Context context, AttributeSet attrs) {
  2.                 super(context, attrs);
  3.                 // TODO Auto-generated constructor stub
  4.             getHolder().addCallback(this);
  5.             canvasthread = new CanvasThread(getHolder(), this);
  6.             setFocusable(true);
  7.         }

And modify the implemented methods to set your threads:

  1.         @Override
  2.         public void surfaceChanged(SurfaceHolder holder, int format, int width,
  3.                         int height) {
  4.                 // TODO Auto-generated method stub
  5.                
  6.         }
  7.         @Override
  8.         public void surfaceCreated(SurfaceHolder holder) {
  9.                 // TODO Auto-generated method stub
  10.             canvasthread.setRunning(true);
  11.             canvasthread.start();
  12.  
  13.                
  14.         }
  15.         @Override
  16.         public void surfaceDestroyed(SurfaceHolder holder) {
  17.                 // TODO Auto-generated method stub
  18.                 boolean retry = true;
  19.                 canvasthread.setRunning(false);
  20.                 while (retry) {
  21.                         try {
  22.                                 canvasthread.join();
  23.                                 retry = false;
  24.                         } catch (InterruptedException e) {
  25.                                 // we will try it again and again...
  26.                         }
  27.                 }
  28.  
  29.         }

Add this class to your project to create threads, which will control the drawings. We need a constructor with the Panel and the SurfaceHolder as parameters, a setter to set the variable which keeps the thread running and we need to override the method run().:

  1. package com.helloandroid.canvastutorial;
  2.  
  3. import android.graphics.Canvas;
  4. import android.view.SurfaceHolder;
  5.  
  6. public class CanvasThread extends Thread {
  7.     private SurfaceHolder _surfaceHolder;
  8.     private Panel _panel;
  9.     private boolean _run = false;
  10.  
  11.     public CanvasThread(SurfaceHolder surfaceHolder, Panel panel) {
  12.         _surfaceHolder = surfaceHolder;
  13.         _panel = panel;
  14.     }
  15.  
  16.     public void setRunning(boolean run) {
  17.         _run = run;
  18.     }
  19.  
  20.     @Override
  21.     public void run() {
  22.         Canvas c;
  23.         while (_run) {
  24.             c = null;
  25.             try {
  26.                 c = _surfaceHolder.lockCanvas(null);
  27.                 synchronized (_surfaceHolder) {
  28.                     _panel.onDraw(c);
  29.                 }
  30.             } finally {
  31.                 // do this in a finally so that if an exception is thrown
  32.                 // during the above, we don't leave the Surface in an
  33.                 // inconsistent state
  34.                 if (c != null) {
  35.                     _surfaceHolder.unlockCanvasAndPost(c);
  36.                 }
  37.             }
  38.         }
  39.     }
  40. }

The last thing, add an onDraw method to your panel:

  1.         @Override
  2.         public void onDraw(Canvas canvas) {
  3.                
  4.                 Paint paint = new Paint();
  5.                
  6.  
  7.                 Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
  8.                                 R.drawable.kangoo);
  9.                 canvas.drawColor(Color.BLACK);
  10.                 canvas.drawBitmap(kangoo, 10, 10, null);
  11.                
  12.         }
  13.          

If you need my image, you can download from here:



Copy this image to drawable folder and refresh your project.

It will draw a kangoo. :) Next time I will show you some drawing commands. Feel free to download the source code from Here.

Comments

If I were to add the above code to a program that has multiple layouts 1 main layout and horizontal and a vertical layout. How does the above code determine which layout to use? Not sure if this is able to work that way?
micheal

شات صوتي

دردشة صوتية

دردشة

دردشه

شات سعودي

شات خليجي
سكر بنات

جات

شات صوتي سعودي خليجي

chat voice

ahj

خليجي الصوتي

سعودي الصوتي

دردشة صوتي

شات صوتي
دردشة صوتية
شات كتابي

شات كتابي خليجي

شات عسل الصوتي

دردشة كتابية

chat
سعودي كول
سعودي كول 6666

كول

سعودي

سعودي كول انحراف

سعودي كول بنات

سعودي كول 1994

سعودي كول 94

شات سعودي كول

سعودي انحراف

سعودي انحراف2010

سعودي انحراف الصوتي

شات سعودي انحراف

دردشة سعودي انحراف

سعودي انحراف الصوتية

شبكة سعودي انحراف

سعودي انحراف الاصلي

سعودي انحراف كول

سعودي انحراف 2010

انحراف سعودي

saudideviation

دردشة صوتية سعوديه
دردشة صوتية سعودية

دردشة كتابية
دردشة كتابية خليجية
شات
دردشة
خاص للبنات

عرب ذوق

عرب ذوق الصوتي

عرب ذوق الصوتية

دردشة عرب ذوق

شات عرب ذوق

شبكة عرب ذوق

شات صوتي بنات

شات بنات الصوتي

دردشة بنات الصوتي

Girls Chat

شبكة عفناك

صوتية عفناك

شات عفناك

دردشة عفناك

عفناك الصوتي

دردشة عفناك

الخيال
الخيال كام
شبكة الخيال
الخيال الصوتي
الخيال الصوتية
دردشة الخيال
الخيال الصوتية
دردشة صوتية الخيال

شات سعودي خليجي

منتدى نونو

منتدى

منتديات

موقع

شبكة

نونو

Chat Nono

ahj w,jd

]v]am w,jdm

دليل مواقع ويب

دليل مواقع

دليل

مواقع

بنت كول
بنت كول الصوتي
شات بنت كول

دردشة بنت كول
شات بنت كول الصوتية

بنت كول الصوتيه
سعودي كول
صوتية سعودي كول
شات سعودي كول
دردشة سعودي كول
سعودي كول الصوتي
سعودي كول 6666
سعودي كول6666
سكر بنات
شات صوتي زين
شات صوتي ملوك
شات صوتي سعودي
شاتات صوتيه
مكتبة ماسنجر
شات صوتي حبي
شات صوتي كويت
YouTube - Broadcast Yourself.‏ , اليوتيوب نونو
صيف كام
شات صوتي كول
شات انحراف
وه بس
خريطة الموقع نونو
الرياض كول الصوتي
كامات 6666
شات المها
كامات6666
شات كامات 6666
كامات 666
كامات 66
سعودي انحراف
شاتكامات6666
سعودي احوه
شات سعودي احوه
سعودي احوه الصوتي
سعودي احوه كول
دردشة سعودي احوه
احوه سعودي
بنات احوه
دبي الصوتي
سعودي في اي بي الصوتي
شبكة الرياض الصوتي
روعة الليل
لايف كام
الخليج كام
شات كان زمان الصوتي
شات صوتي قصيمي
شات قلبي
ارجوان
شات صوتي قطري
بدور الخليج

منتدى روح

شبكة روح

روح ديزاين

تحميل ماسنجر بلس

توبيكات حزينه

توبيكات

ماسنجر

ماسنجر بلس

تحميل ماسنجر

توبيكات رومنسيه

منتديات روح
دردشة
شات سعودي
خليجي
شات صوتي
سعودي انحراف 2010 , صوتية سعودي انحراف , شبكة سعودي انحراف , موقع سعودي انحراف , سعودي انحراف لايف , مواقع انحرافية , دردشة شات سعودي انحراف الصوتي , سعودي لايف 2010 , سعودي انحراف 2011 , بنات لايف , منحرفات لايف جاتسعودي انحراف 6666- سعودي انحراف 2010 - سعودي انحراف2010 - سعودي انحراف 2007 - سعودي فور انحراف - سعودي انحراف - Saudi an7raf سعودي انحراف , deviation Saudi 2010‏ دردشة, شات, سعودي, انحراف 2010, كامات, ,شات انحرافي saudi, an7raf, deviation.‏ سعودي انحراف , انحراف , An7raf 6666‏سعودي انحراف , شات سعودي انحراف , شات انحرافي , انحراف 2010سعودي انحراف , سعودي انحراف 2010 , chat saudi an7raf , saudi ...‏

!

In this way i can use canvas on my android smartphone, thanks a lot!

Mercedes

You can make use of many software programs to do sewing and canvasing but there is no substitute for hand-made art work. If you are keen on learning quilt patterns then you can learn basics on TV while opting for classes later on.

Completely I share your opini on. In it something is and it is excellent idea. I support you.
itunes drm remover, itunes video converter, convert dvd to itunes how to put youtube video on ipod touch.

Well, I am so excited that I have found this your post because I have been searching for some information about it almost three hours. You helped me a lot indeed and reading this your article I have found many new and useful information about this subject. the diet solution

Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
garden treasures

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: kitchen worktops

We can give them a good education that they can use in their life to get a better chance in this life. Im sure with a good education all of us will see the changing that all that kids can have. Mac DVD Ripper

Companies these days are using ergonomic furniture to ensure that there are no injuries from work related hazards. Use an ergonomic chair and feel better comfort in your back and shoulder. oxyhives

If I add f.e. ImageView to main.xml I can simply get to it from Canvastutorial class by
ImageView iv = (ImageView)findViewById(R.id.imageView);

How can I do this from Panel class?

We can give them a good education that they can use in their life to get a better chance in this life. Im sure with a good education all of us will see the changing that all that kids can have. Ross Mccarthy

There is an article that gives great insight to foundational elements when it comes to being able to successfully make money on the internet. wall stickers

If I were to add the above code to a program that has multiple layouts 1 main layout and horizontal and a vertical layout. How does the above code determine which layout to use? Not sure if this is able to work that way?

Companies these days are using ergonomic furniture to ensure that there are no injuries from work related hazards. Use an ergonomic chair and feel better comfort in your back and shoulder. lexikon

Companies these days are using ergonomic furniture to ensure that there are no injuries from work related hazards. Use an ergonomic chair and feel better comfort in your back and shoulder. Mattress Protector

it is sometimes hard to Pandora in a world of adults Pandora Bracelets

Thank alot for this code and information.
Fitness

I'm new for android.
when I read your code I don't understand this declaration in xml file

com.helloandroid.canvastutorial.Panel
android:id="@+id/SurfaceView01" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxHeight="40dip">
com.helloandroid.canvastutorial.Panel

what does "com.helloandroid.canvastutorial.Panel " mean, I've never seen the declaration like this before?
Can you explain how the program run?

Thanks you very much

hey asbk1987

com.helloandroid.canvastutorial is your project name and the Panel is the class you want to show in that project.

greets
MatthiasW