canderse
canderse

Reputation: 319

MonoTouch Making a UIImage from a CIImage causes an invalid argument / bad selector

I am trying to create a blured background when I show a popover I almost got it to work.

I found some Objective C which I translated into C#.

the problem is in this line

UIImage finalImage = new UIImage(resultImage);

hope it is just something I am doing wrong

    private UIView CreateBlurView(UIView view)
    {
        UIGraphics.BeginImageContext(view.Bounds.Size);
        view.Layer.RenderInContext(UIGraphics.GetCurrentContext());
        UIImage viewImage = UIGraphics.GetImageFromCurrentImageContext();

        // Blur Image
        CIImage imageToBlur = CIImage.FromCGImage(viewImage.CGImage);
        CIFilter gaussianBlurFilter = CIFilter.FromName("CIGaussianBlur");
        gaussianBlurFilter.SetValueForKey(imageToBlur,new NSString("inputImage"));
        gaussianBlurFilter.SetValueForKey(new NSNumber(10.0f),new NSString("inputRadius"));
        CIImage resultImage = (CIImage) gaussianBlurFilter.ValueForKey(new NSString("outputImage"));

        UIImage finalImage = new UIImage(resultImage);
        UIImageView  imageView = new UIImageView(view.Bounds);
        imageView.Image = finalImage;
        return imageView;
    }

Upvotes: 1

Views: 968

Answers (1)

poupou
poupou

Reputation: 43553

First make sure you're using iOS 6 (or later) since CIGaussianBlur was not available in iOS before that version.

Next, you're missing (from the original code) the line:

UIGraphicsEndImageContext();

which in C# / MonoTouch should be:

MonoTouch.UIKit.UIGraphics.EndImageContext ();

Finally you hit a bug :(

-[UIImage initWithCIImage]: unrecognized selector sent to instance 0x168f2280

a : is missing at the end of the selector. Now there's another .ctor that accept a CIImage along with a float (scale) and a UIImageOrientation. This one should work properly.

The full source would be:

private UIView CreateBlurView(UIView view)
{
    UIGraphics.BeginImageContext(view.Bounds.Size);
    view.Layer.RenderInContext(UIGraphics.GetCurrentContext());
    UIImage viewImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext ();

    // Blur Image
    CIImage imageToBlur = CIImage.FromCGImage(viewImage.CGImage);
    CIFilter gaussianBlurFilter = CIFilter.FromName("CIGaussianBlur");
    gaussianBlurFilter.SetValueForKey(imageToBlur,new NSString("inputImage"));
    gaussianBlurFilter.SetValueForKey(new NSNumber(10.0f),new NSString("inputRadius"));
    CIImage resultImage = (CIImage) gaussianBlurFilter.ValueForKey(new NSString("outputImage"));

    UIImage finalImage = new UIImage(resultImage, 1.0f, UIImageOrientation.Up);
    UIImageView  imageView = new UIImageView(view.Bounds);
    imageView.Image = finalImage;
}

Note: the typo has been fixed in MonoTouch and the constructor will be usable in future releases (6.0.9+)

Upvotes: 3

Related Questions