How to draw a Bitmap or Image drawable in Android Canvas

In this android programming source code example, we are going to draw a Bitmap or Image drawable in Android Canvas.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to draw a Bitmap or Image drawable in Android Canvas.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;


public class CanvasActivity7 extends AppCompatActivity {
    private ImageView img;
    private int offset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas7);
        img = (ImageView) findViewById(R.id.image);
        offset = 50;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profilepic);
        Bitmap dstBitmap = Bitmap.createBitmap(bitmap.getWidth() + offset * 2, bitmap.getHeight() + offset * 2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(dstBitmap);
        canvas.drawColor(Color.LTGRAY);
        canvas.drawBitmap(bitmap, offset, offset, null);
        img.setImageBitmap(dstBitmap);
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment