Why does UIGraphics.GetCurrentContext return null?

I have a UIViewController that contains 2 subviews (classes derived from UIView) that execute a custom drawing using UIGraphics.GetCurrentContext. The drawing works great when the application starts. I connect subviews in a viewDidLoad () view controller as follows:

DigitalNumberView dnv = new DigitalNumberView(); dnv.Frame = new System.Drawing.RectangleF(10, 10, 750, 190); View.AddSubview(dnv); CircleView tuner = new CircleView(dnv); tuner.Frame = new System.Drawing.RectangleF(570, 220, 190, 190); View.AddSubview(tuner); 

I need the first subtitle to draw custom stuff depending on what the second preview does. When the second subview gets TouchesEnded, I call the function in the first view, which displays the new data. In the drawing, the first preview uses UIGraphics.GetCurrentContext, which gets zero in this particular workflow. Here is an example of how he draws:

 SetNeedsDisplay(); CGContext context = UIGraphics.GetCurrentContext (); if (null == context) { Console.WriteLine("Retrieved null CGContext"); return; } RectangleF r = new RectangleF(25, 10, 180, 180); ClearNumber(context, r); DisplayNumber(context, f, r); UIGraphics.EndImageContext(); 

Why does UIGraphics.GetCurrentContext return null only in this workflow, but not on startup? Is there any other way to achieve the same result? Did I miss something?

+4
source share
2 answers

You should not do this, what you want to do is override:

  public virtual void Draw (System.Drawing.RectangleF rect) 

in your UIView subclasses, and when the method is raised (in response to SetNeedsDisplay ()), do your whole drawing.

+5
source

If you are drawing on UView, then subclass it and use the Draw method.

If you need context, you need to start it first. Like (taken from my code, drawingBoard is UIImage and drawingView is UIImageView UIImage):

 UIGraphics.BeginImageContext (drawingBoard.Size); // erase lines ctx = UIGraphics.GetCurrentContext (); // Convert co-ordinate system to Cocoa (origin in UL, not LL) ctx.TranslateCTM (0, drawingBoard.Size.Height); ctx.ConcatCTM (CGAffineTransform.MakeScale (1, -1)); ctx.DrawImage (new RectangleF (0, 0, drawingBoard.Size.Width, drawingBoard.Size.Height), drawingBoard.CGImage); drawingBoard = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); drawingView.Image = drawingBoard; 
+1
source

Source: https://habr.com/ru/post/1341566/


All Articles