Blogger Tips and TricksLatest Tips And TricksBlogger Tricks

Write an application that draws basic graphical primitives on the screen in android

1)Open eclipse or android studio and select new android project
2)Give project name and select next
3) Choose the android version.Choose the lowest android version(Android 2.2) and select next
4) Enter the package name.package name must be two word seprated by comma and click finish
5)Go to package explorer in the left hand side.select our project.
6)Go to res folder and select layout.Double click the main.xml file.Don't change anything in layout.Leave as default.
7) Now select mainactivity.java file and type the following code.
package Basic.primitive;
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.View;
public class BasicprimitiveActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new myview(this));
                     }
    private class myview extends View
    {
        public myview(Context context)
        {
        super(context);
        }
        @Override
         protected void onDraw(Canvas canvas)
        {
            super.onDraw(canvas);
            Paint paint=new Paint();
            paint.setTextSize(40);
            paint.setColor(Color.GREEN);
            canvas.drawText("Circle", 55, 30, paint);
            paint.setColor(Color.RED);
            canvas.drawCircle(100, 150,100, paint);
            paint.setColor(Color.GREEN);
            canvas.drawText("Rectangle", 255, 30, paint);
            paint.setColor(Color.YELLOW);
            canvas.drawRect(250, 50,400,350, paint);
            paint.setColor(Color.GREEN);
            canvas.drawText("SQUARE", 55, 430, paint);
            paint.setColor(Color.BLUE);
            canvas.drawRect(50, 450,150,550, paint);
            paint.setColor(Color.GREEN);
            canvas.drawText("LINE", 255, 430, paint);
            paint.setColor(Color.CYAN);
            canvas.drawLine(250, 500, 350, 500, paint);          
        }
         }
}
8)Now go to main.xml and right click .select run as option and select run configuration
9) Android output is present in the android emulator as shown in below.


No comments:

Post a Comment

Flag Counter