Drawing to Canvas on Android – Code Example

Draw full screen on your Android phone

This is just example code. For a throughout explanation, see Make Arduino Bots and Gadgets: Boxing Clock.

package com.botbook.drawingoncanvas;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

//Copyright 2011 Tero Karvinen http://botbook.com

public class DrawingOnCanvasActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 fullscreen(); // without this, bottom of canvas goes out of screen
 TCanvas tCanvas = new TCanvas(this);
 setContentView(tCanvas);
 }

 public void fullscreen()
 {
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
 WindowManager.LayoutParams.FLAG_FULLSCREEN);
 }

 public class TCanvas extends View {
 public TCanvas(Context context) {
 super(context);
 }

 public void onDraw(Canvas c) {
 c.drawColor(Color.BLUE);

 Paint paint = new Paint();
 paint.setStyle(Paint.Style.FILL);
 paint.setAntiAlias(true);

 paint.setColor(Color.RED);
 c.drawCircle(0, 0, 50, paint);
 paint.setColor(Color.WHITE);
 paint.setTextSize(20);
 c.drawText("0,0 is top left", 0, 0+20, paint);

 float w=c.getWidth();
 paint.setColor(Color.GREEN);
 c.drawCircle(w, 0, 50, paint);
 paint.setColor(Color.WHITE);
 paint.setTextAlign(Align.RIGHT);
 c.drawText("right: x is width", w, 0+20, paint);

 float h=c.getHeight();
 paint.setColor(Color.YELLOW);
 c.drawCircle(w/2, h, 200, paint);
 paint.setColor(Color.BLACK);
 paint.setTextAlign(Align.CENTER);
 c.drawText("bottom: y is height, center: half of width", w/2, h-20, paint);
 }
 }
}

More Draw Commands for Canvas

You can see all available draw-commands with ctrl-space: Type the name of your canvas object in Eclipse. Just type “.draw” and press control space.

See Also

Make Arduino Bots and Gadgets: Boxing Clock. (Book on Amazon)

Boxing Clock for Android (Code examples)

Posted in Uncategorized | Tagged , , , , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Picks

  • Boxing Clock for AndroidOcton8 Diving T-ShirtsShaking Tower Panda Android GameLearn Chinese with Android
  • Student projects