Graphics in Android Using OnDraw() Method and Paint Class -Simple Example

Posted on .
androidarena_graphics

Hello nerds! Today I am going to show you how to play with graphics in Android using OnDraw() and Paint Class . It is very simple to go through with it , I am going to provide you a simple tutorial on that but you can change and can do experiments according to your choice.

You can download the source code here and make experiments according to your need.

Download Code

Here in this project we don’t need any kind of xml layout file we can create it through Java file or we can say dynamically . Create your project with your desire name and see on my

MainActivity.java .

package com.example.simplegraphics;

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.Menu;
import android.view.View;

public class MainActivity extends Activity {

	DemoView demo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		demo = new DemoView(this);
		setContentView(demo);
	}

	private class DemoView extends View {
		public DemoView(Context mcontext) {
			super(mcontext);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			// custom drawing code here
			Paint paint = new Paint();
			paint.setStyle(Paint.Style.FILL);

			// make the entire canvas white
			paint.setColor(Color.CYAN);
			canvas.drawPaint(paint);

			// draw blue circle with anti aliasing turned off
			paint.setAntiAlias(false);
			paint.setColor(Color.MAGENTA);
			canvas.drawCircle(20, 20, 15, paint);

			// draw green circle with anti aliasing turned on
			paint.setAntiAlias(true);
			paint.setColor(Color.GRAY);
			canvas.drawCircle(60, 20, 15, paint);

			// draw red rectangle with anti aliasing turned off
			paint.setAntiAlias(false);
			paint.setColor(Color.RED);
			canvas.drawRect(100, 5, 200, 30, paint);

			// draw the rotated text
			canvas.rotate(-40);

			paint.setStyle(Paint.Style.FILL);
			canvas.drawText("Graphics Rotation", 45, 185, paint);

			// undo the rotate
			canvas.restore();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Here in this example we use Paint class and by using object of paint we can set anything like above i mention like setColor,setStyle and by using Canvas object we can draw drawcircle,rectangle etc.

 

OutPut –

output_graphics_androidarena

 

If you have any query feel free to ask anything 🙂

 

2 thoughts on “Graphics in Android Using OnDraw() Method and Paint Class -Simple Example

Leave a Reply

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