SoFunction
Updated on 2025-04-10

Examples of basic usage of drawing canvas for Android programming

This article describes the basic usage of drawing canvas in Android programming. Share it for your reference, as follows:

The code of MainActivity is as follows:

package ;
import ;
import ;
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    //Instantiate GraphicsView    GraphicsView gv = new GraphicsView(this);
    /* In the past we displayed the layout file through setContentView(.activity_main)
      * In this example, use the GraphicsView object gv instead of the previous layout file
      */
    setContentView(gv);
  }
}

Another class class that defines canvas brushes

GraphicsView

The code is as follows:

package ;
import ;
import ;
import ;
import ;
import ;
public class GraphicsView extends View{
  //Declare the brush  Paint paint=null;
  public GraphicsView(Context context) {
    super(context);
    /*----------------------------------------------
      * In some books, Paint paint=new Paint(); is placed in the onDraw method. It is recommended that
      * Try not to put the initialization brush in the onDraw method, this is because onDraw often runs
      * If you arrive, don't use new objects in it, the fewer the better, otherwise it will waste memory
      *---------------------------------------------*/
    //Get the brush and initialize the brush    paint=new Paint();
  }
  @Override
  protected void onDraw(Canvas canvas){
    //Set the canvas background to white    ();
    //Set the brush to red    ();
    // Use the current brush to draw a rectangle with the upper left coordinates of 80,20 and the lower right coordinates of 360,180    (80,20,360,180, paint);
    //Set the brush to green    ();
    // Use the current brush to draw a circle with a center coordinate of 220,100 and a radius of 60    (220,100, 60, paint);
  }
}

For more information about Android related content, please check out the topic of this site:Summary of Android graphics and image processing skills》、《Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.