Unexpected null reference exception.

DeanCleaverDeanCleaver USMember ✭✭✭

I have this code:

UIImage scaledImage;

if (photo.Size.Width > photo.Size.Height)
    scaledImage = photo.Scale(new SizeF(1024, 768));
else
    scaledImage = photo.Scale(new SizeF(768, 1024));

scaledImage = AddDate(scaledImage);

And AddDate looks like this:

public static UIImage AddDate(UIImage original)
{
    int width = (int) original.Size.Width;

        // Other code
}

I got a null reference exception on that first line in AddDate. So, either original was null, or Size was null. If Size was null, how is that possible? And if original is null, then photo.Scale must have returned null - how (why?) can that occur?

Posts

  • adamkempadamkemp USInsider, Developer Group Leader mod

    If you look at the implementation of the Scale method in Xamarin.iOS it's doing this:

    public UIImage Scale(SizeF newSize)
    {
        UIGraphics.BeginImageContext(newSize);
        this.Draw(new RectangleF(0f, 0f, newSize.Width, newSize.Height));
        UIImage imageFromCurrentImageContext = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return imageFromCurrentImageContext;
    }
    

    This is just a guess, but maybe you already have an active drawing context, and so BeginImageContext is failing. Check your call stack and see whether that might be happening.

    As an alternative implementation I think you could use UIImage.FromImage(originalImage.CGImage, scale, UIImageOrientation.Up).

  • DeanCleaverDeanCleaver USMember ✭✭✭

    Would it fail silently? I have no calls to BeginImageContext in my code, but that's not to say there isn't one somewhere as this is in a view controller that uses the camera to capture images etc.

    And it's not always happening - just occasionally. Very frustrating.

  • adamkempadamkemp USInsider, Developer Group Leader mod

    To be clear, I don't mean specifically a call to BeginImageContext. I mean any drawing context. If you're in the middle of drawing a view (i.e., a UIView's Draw method is in the call stack) then you're in an active CGContext. I don't know if those can be nested so maybe in that case BeginImageContext fails because it tries to set the current CGContext when you already have one.

  • DeanCleaverDeanCleaver USMember ✭✭✭

    Ah - ok - thanks for the clarification. That could well be it - the view with the camera on it could be closing at the time the system is processing the image etc. I will look to see if I have other options, like the FromImage scale method you mentioned.

Sign In or Register to comment.