MonoTouch如何将带有透明度的彩色UIImage转换为灰度模糊图像?

9

我正在寻找一种从彩色PNG和Alpha生成模糊灰度UIImage的配方。在ObjC中有这样的配方,但是MonoTouch没有绑定CGRect函数,所以不确定如何处理。您有什么想法吗?

这里是一个ObjC灰度示例:

(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;
}

我尝试使用这个函数,但它不能处理除了1.0比例以外的图像...(在Retina上会出错) - Jonny
2个回答

13
使用MonoTouch时,CGRect 被映射到 RectangleF。许多扩展方法存在,应该可以将它们映射到由 GCRect 提供的每个函数。使用这些方法,您在移植 Objective-C 代码时不应遇到任何问题。
如果有缺少的功能,请在 http://bugzilla.xamarin.com 上填写错误报告,我们会尽快修复(并在可能情况下提供解决方案)。
如果你有链接,请编辑你的问题并添加链接。这将更容易帮助你:) 更新: 这里是你的示例逐行翻译成 C# 的结果。它对我来说似乎工作正常(比 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);
        }
    }

非常好!我想我可能需要花更多时间学习翻译 ObjC 的示例,因为显然它可以变得很容易(就像你刚才做的那样)。谢谢。 - Sheldon Hage
很高兴它能为您正常工作 :-) 请花点时间接受答案(绿色标记在投票数字下面)以便其他搜索类似问题的人可以看到有一个可用的答案。 - poupou

0

我为Monotouch编写了WWDC的模糊和色调UIImage类别的本地端口。

渲染和模糊的示例代码:

UIColor tintColor = UIColor.FromWhiteAlpha (0.11f, 0.73f);

UIImage yourImage;
yourImage.ApplyBlur (20f /*blurRadius*/, tintColor, 1.8f /*deltaSaturationFactor*/, null);

你应该将deltaSaturationFactor设置为0。 - evya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接