Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

How to draw a rectangle on a canvas in Android

Posted on October 10, 2017August 4, 2020 by Habibie

Instead of showing default activity layout, we can create our custom class. Here in this example I’m going to share a script to draw a rectangle on a canvas in Android.

This codes for your Main Activity:

package com.zofiakreasi.canvastest;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

    }
}

And this one for your custom class called CustomView.java

package com.zofiakreasi.canvastest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

/**
 * Created by user on 10/10/2017.
 */
public class CustomView extends View {
    private Rect rectangle;
    private Paint paint;

    boolean notRunning = false;

    public CustomView(Context context){
        super(context);
        int x = 50;
        int y = 50;
        int sideLength = 200;

        //create rectangle
        rectangle = new Rect(x, y, sideLength, sideLength);

        //create paint and set its color
        paint = new Paint();
        paint.setColor(Color.GRAY);

    }

    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawColor(Color.BLUE);
        canvas.drawRect(rectangle, paint);
    }
}
Post Views: 375
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Hover Reveal script for Unity to show and hide object on mouse hover
  • How to Prevent UI Clicks in Unity from “Bleeding Through” to 3D Objects Behind Them
  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
© 2026 ThirteeNov | Powered by Superbs Personal Blog theme