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:
- Create a new Xamarin.Android application named
TwoDDrawing
. Notice that the project name does not start with a number. - Delete
Main.axml
, it is not necessary for this recipe. - Create a new class in the project named
MyOvalShape
, have it extendAndroid.Views.View
, and implement a constructor that takes aAndroid.Content.Context
:
public class MyOvalShape : View
{
public MyOvalShape(Context context) : base(context) { }
}
- Add an instance variable to the class:
private readonly ShapeDrawable _shape;
- 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);
}
- Override
OnDraw
insideMyOvalShape
, this will draw the oval:
protected override void OnDraw(Canvas canvas)
{
_shape.Draw(canvas);
}
- 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));
}
- Run the application on a device, and an oval shape will be drawn:
ShapeDrawable
is an extension of the Drawable
class
which defines some basic geometric shapes such as arcs, ovals, and
rectangles.