Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would UIGraphics.GetCurrentContext return null?

I've got a UIViewController that contains 2 subviews (classes derived from UIView) that do custom drawing with UIGraphics.GetCurrentContext. The drawing works fine at application startup. I connect the subviews in the view controller's ViewDidLoad() like this:

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 subview to draw custom stuff depending on what the second subview does. When the second subview gets a TouchesEnded, I call a function in the first subview that displays new data. The drawing in the first subview uses UIGraphics.GetCurrentContext, which is getting null in this specific workflow. Here's a sample of how it 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 at startup? Is there another way to achieve this same result? Am I just missing something?

like image 582
Jim Avatar asked Feb 28 '11 00:02

Jim


2 Answers

You shouldn't be doing that, what you want to do is override the:

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

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

like image 142
Geoff Norton Avatar answered Oct 06 '22 09:10

Geoff Norton


If you draw to the UView, then subclass it and use the Draw method.

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

UIGraphics.BeginImageContext (drawingBoard.Size);

// erase lines
ctx = UIGraphics.GetCurrentContext ();

// Convert co-ordinate system to Cocoa's (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;
like image 20
Pavel Sich Avatar answered Oct 06 '22 08:10

Pavel Sich