Drawing on the canvas of a View
Sometimes using the animation and shape APIs are not enough to create the image or app that we want to create. This may be to create a game or draw a complex image.
How to do it...
Drawing to a canvas can be easily done by creating a new view that derives from View
, and then overriding the OnDraw()
method:
- First, we will need our custom
View
instance that implements the constructors that allow us to instantiate the view from either code or a layout file:public class CustomView : View { public CustomView(Context context) : base(context) { } public CustomView(Context context, IAttributeSet attrs) : base(context, attrs) { } public CustomView( Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } }
- Next, we override the
OnDraw()
method. This method draws the actual frame and will be called each time the view needs refreshing:protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); }
- Drawing...