Skip to content
This repository has been archived by the owner on Oct 20, 2022. It is now read-only.

Latest commit

 

History

History

draw_2d_graphics

id title sdk
6EFBBBBF-2B2B-2F77-E796-03392B93A2F2
Draw 2D Graphics

This recipe will provide an example of drawing a simple 2-D object.

Related Google Documentation:

Recipe

  1. Create a new Xamarin.Android application named TwoDDrawing . Notice that the project name does not start with a number.
  2. Delete Main.axml , it is not necessary for this recipe.
  3. Create a new class in the project named MyOvalShape , have it extend Android.Views.View , and implement a constructor that takes a Android.Content.Context :
public class MyOvalShape : View
{
    public MyOvalShape(Context context) : base(context) { }
}
  1. Add an instance variable to the class:
private readonly ShapeDrawable _shape;
  1. Add the following code into the constructor of MyOvalShape to create the shape that is to be drawn:
public MyOvalShape(Context context) : base(context)
{
    var paint = new Paint();
    paint.SetARGB(255, 200, 255, 0);
    paint.SetStyle(Paint.Style.Stroke);
    paint.StrokeWidth = 4;

    _shape = new ShapeDrawable(new OvalShape());
    _shape.Paint.Set(paint);

    _shape.SetBounds(20, 20, 300, 200);
}
  1. Override OnDraw inside MyOvalShape, this will draw the oval:
protected override void OnDraw(Canvas canvas)
{
    _shape.Draw(canvas);
}
  1. Modify Activity1.OnCreate so that the oval will be drawn when the application starts:
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(new MyOvalShape(this));
}
  1. Run the application on a device, and an oval shape will be drawn:

Additional Information

ShapeDrawable is an extension of the Drawable class which defines some basic geometric shapes such as arcs, ovals, and rectangles.