Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MonoTouch convert color UIImage with alpha to grayscale and blur?

I am trying to find a recipe for producing a a blurred grayscale UIImage from a color PNG and alpha. There are recipes out there in ObjC but MonoTouch does not bind the CGRect functions so not sure how to do this. Any ideas?

Here is one ObjC example of grayscale:

(UIImage *)convertImageToGrayScale:(UIImage *)image
{
  // Create image rectangle with current image width/height
  CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);

  // Grayscale color space
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

  // Create bitmap content with current image size and grayscale colorspace
  CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0,   colorSpace, kCGImageAlphaNone);

  // Draw image into current context, with specified rectangle
  // using previously defined context (with grayscale colorspace)
  CGContextDrawImage(context, imageRect, [image CGImage]);

  // Create bitmap image info from pixel data in current context
  CGImageRef imageRef = CGBitmapContextCreateImage(context);

  // Create a new UIImage object  
  UIImage *newImage = [UIImage imageWithCGImage:imageRef];

  // Release colorspace, context and bitmap information
  CGColorSpaceRelease(colorSpace);
  CGContextRelease(context);
  CFRelease(imageRef);

  // Return the new grayscale image
  return newImage;
}
like image 283
Sheldon Hage Avatar asked Dec 20 '11 15:12

Sheldon Hage


1 Answers

Monotouch does not bind the CGRect functions so not sure how to do this.

When using MonoTouch CGRect is mapped to RectangleF. A lot of extension methods exists that should map to every function provided by GCRect. You should not have any problem in porting ObjectiveC code using them.

If something is missing please fill a bug report @ http://bugzilla.xamarin.com and we'll fix it asap (and provide a workaround when possible).

There are recipes out there in ObjC but MonoTouch

If you have links then please edit your question and add them. That will make it easier to help you :)

UPDATE

Here's a, line-by-line, C# translation of your example. It seems to works for me (and it's much easier to my eyes than Objective-C ;-)

    UIImage ConvertToGrayScale (UIImage image)
    {
        RectangleF imageRect = new RectangleF (PointF.Empty, image.Size);
        using (var colorSpace = CGColorSpace.CreateDeviceGray ())
        using (var context = new CGBitmapContext (IntPtr.Zero, (int) imageRect.Width, (int) imageRect.Height, 8, 0, colorSpace, CGImageAlphaInfo.None)) {
            context.DrawImage (imageRect, image.CGImage);
            using (var imageRef = context.ToImage ())
                return new UIImage (imageRef);
        }
    }
like image 117
poupou Avatar answered Nov 08 '22 02:11

poupou