How to make rectangle shape with color filled using bitmap and canvas on button click dynamically.
In this tutorial we are crating an Rectangle shape using bitmap and canvas. Firstly we have created an bitmap size of 400 × 250 and after that filling this bitmap with background color using canvas then set this bitmap into image view. So here is the complete step by step tutorial for Create Draw 2d Rectangle shape in android programmatically.
How to Create Draw 2d Rectangle shape in android programmatically.
Code for MainActivity.java file.
package com.draw2drectangleshape_android_examples.com; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { ImageView imageview; Button button; Bitmap bitmap; Canvas canvas; Paint paint; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button1); imageview = (ImageView)findViewById(R.id.imageView1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub bitmap = Bitmap.createBitmap( 400, 250, Bitmap.Config.RGB_565); canvas = new Canvas(bitmap); canvas.drawColor(Color.CYAN); imageview.setImageBitmap(bitmap); } }); } }
Code for activity_main.xml layout file.
<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="com.draw2drectangleshape_android_examples.com.MainActivity" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Click here to Draw 2d Rectangle shape in android programmatically" /> </RelativeLayout>
Screenshot: