How to Draw Shapes in Android

In this tutorial how to create Splash Screen is shown.

Points to Remember:

  • To view the shapes filled with color then change the paint style to Paint.Style.FILL instead of Paint.Style.STROKE.

Code:

activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity” >

</RelativeLayout>

 

MainActivity.java

package com.example.demo;

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

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new myView(this));
}

private class myView extends View{

Paint myPaint,myPaint1,myPaint2;

public myView(Context context)
{
super(context);
myPaint=new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
myPaint1=new Paint();
myPaint1.setColor(Color.BLUE);
myPaint1.setStyle(Paint.Style.STROKE);
myPaint1.setStrokeWidth(3);
myPaint2=new Paint();
myPaint2.setColor(Color.RED);
myPaint2.setStyle(Paint.Style.STROKE);
myPaint2.setStrokeWidth(3);
}

@Override
protected void onDraw(Canvas canvas){
canvas.drawColor(Color.YELLOW);
canvas.drawRect(10,10,100,100, myPaint);
canvas.drawRect(190, 10, 250, 100, myPaint1);
canvas.drawRect(300, 10, 450, 100, myPaint1);
canvas.drawLine(10, 120, 470, 120, myPaint);
canvas.drawLine(150, 10, 150, 120, myPaint);
canvas.drawCircle(250, 400, 150, myPaint2);
}

}

@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;
}
}

Add a Comment

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