logo
Login

Sponsored Links

Sponsored

Building Paint like Application in Android

Android Paint AppWhat was the first thing that you did when you logged on to a Computer the first time? For me, it was Microsoft Paint. As a child who never drew a circular-circle in her entire life, it was exciting to draw perfect circles, rectangles and straight lines. And now when I see kids painting their first painting on an Android app it reminds me of my childhood. So for this tutorial I am going to create a simple paint-brush app. This app is very simple but it will give you a basic idea about how to use the Android API to make a paint app. So lets get it started!!

Step-1: Create the Project in Eclipse

As seen in the previous tutorials the project can be created in Eclipse after you have installed the android plugin for eclipse.

Creating the Paint brush project

The maifest file is the default one. It should look like this:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="org.developerfeed.ankita.mypaintbrush"
   android:versionCode="1"
   android:versionName="1.0" >
    <uses-sdk
       android:minSdkVersion="8"
       android:targetSdkVersion="17" />
    <application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
        <activity
           android:name="org.developerfeed.ankita.mypaintbrush.PaintActivity"
           android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
 

Step -2: The View

For the paint brush application, view is the most important element. Here we are not going to rely on the XML view and we will create a custom view instead. To create a custom view, we need a Java class which extends android.view.View. Initally the class should look like the following code:


package org.developerfeed.ankita.mypaintbrush;
import android.content.Context;
import android.view.View;
public class BrushView extends View {
        public BrushView(Context context) {
        super(context);
    }
}
 

Paint and Path

The magic ingredient in this app is the android.graphics.Paint class. This class has the methods we will need to use to paint on this canvas. Also we need an object of class android.graphics.Path. According to Android documentation, this class is responsible for encapsulating compound geometric paths consisting of straight line segments, quadratic curves, and cubic curves. Sonds complicated but really for our app it will just tell us the path user draws using the touch screen.


    private Paint brush = new Paint();
    private Path path = new Path();
 

Along with these two objects I think we should also add a simple reset button for now. So take an object of Button class too. And a LayoutParams object to setup the button parameters. So now your view should look like
this.


package org.developerfeed.ankita.mypaintbrush;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
public class BrushView extends View {
    private Paint brush = new Paint();
    private Path path = new Path();
    public Button btnEraseAll;
    public LayoutParams params;
    public BrushView(Context context) {
        super(context);
        brush.setAntiAlias(true);
        brush.setColor(Color.BLUE);
        brush.setStyle(Paint.Style.STROKE);
        brush.setStrokeJoin(Paint.Join.ROUND);
        brush.setStrokeWidth(10f);
        btnEraseAll=new Button(context);
        btnEraseAll.setText("Erase Everything!!");
        params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        btnEraseAll.setLayoutParams(params);
    }
}
 

Click Event of the Button

Next thing that you need a simple click event for the button so you can add that to the constructor like this:


        btnEraseAll.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View view) {
                //reset the path
                path.reset();
                //invalidate the view
                postInvalidate();
               
            }
        });
 

Wow we are making progress aren't we? But still the output is nowhere to be seen! Patience dear friends, we shall achieve our goal soon.

The Making of the Path

A Path object just encapsulates a path. We need to add points to the path as the user touches the screen and drags his/her fingers. So we need to handle some event of the View which can tell us about the area being touched by the user. That event is called onTouchEvent and we need to add a method to out view for handling it. Here it code to get it started.


@Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
   
    }
 

This method will help us in creating the path which will later be painted using another method. MotionEvent will be hadled like this:

We start creating a path when the user first touches the screen (ie MotionEvent.ACTION_DOWN). As he/she drags it we keep adding the points into the path (ie MotionEvent.ACTION_MOVE) and when the user stops, we stop adding points and invalidate the view forcing it to repaint. Let us see the implementation:


public boolean onTouchEvent(MotionEvent event) {
        float pointX = event.getX();
        float pointY = event.getY();
        // Checks for the event that occurs
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            path.moveTo(pointX, pointY);
            return true;
        case MotionEvent.ACTION_MOVE:
            path.lineTo(pointX, pointY);
            break;
        default:
            return false;
        }      
         // Force a view to draw again
        postInvalidate();
        return false;
    }
 

The Actual Painting

Now for the view the last element is the actual painting. That will be handled by overriding onDraw like this:


@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, brush);
    }
 

So far so good. Now on to the next step!

Step-3 Using the View

Any view can be used by associating it with an activity. And that is what we are going to do. So create an Activity class named PaintActivity. And in the constructor set the layout of this activity as an object of our custom view class.

Th activity looks as follows:


package org.developerfeed.ankita.mypaintbrush;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class PaintActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BrushView view=new BrushView(this);
        setContentView(view);
        addContentView(view.btnEraseAll, view.params);
    }
    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}
 

Voila! We are done. Now lets see the output shall we. Run the project in you AVD and look at your handy work.

The Output

the output of me saying hello

Wow we are done. Onwards to the next conquest!

The complete Android project for this tutroail is attached to the post.

AttachmentSize
MyPaintBrush.zip1.06 MB
Like Developerfeed? Follows us via: RSS Feed Follow me on Twitter! Follow me on Facebook! Follow me on Youtube!

Socialize & Share Now :

Subscribe to DeveloperFeedDid you like this article? Did it Help you Solve your Problem? You can get the all the latest articles published at DeveloperFeed in your email inbox by entering your email address below. Your address will only be used for mailing you the articles, and each one will include a link so you can unsubscribe at any time.

Enter your email address:

Ryan Pringnitz's picture
 #

Loved this tutorial. First time using the canvas class and it was easier than I had thought.

 

Subscribe & Follow

RSS Feed Follow me on Twitter! Follow me on Facebook! Follow me on Youtube!
Feed via Email:

Sponsored Links

Facebook

Sponsored Apps

Job Change Alert for Linkedin


Contact2CRM for Salesforce


Advertise on DeveloperFeed

About

Manpreet is an Architect & Software developer currently focusing on developing mobile apps on the iOS (iPhone/iPad) Platform. He’s the founder of a small iPhone development studio
called Livrona.

Subscribe to Developer Feed iPhone Blog

Tags

Who's online

There are currently 0 users and 4 guests online.