objective-c - 在 Monotouch 中调整大小并将图像保存到磁盘

标签 objective-c resize uiimage xamarin.ios

我正在尝试调整从磁盘加载的图像的大小 - JPG 或 PNG(加载时我不知道格式)- 然后将其保存回磁盘

我有以下代码,我试图从 objective-c 移植这些代码,但是我卡在了最后一部分。 Original Objective-C .

这可能不是实现我想要做的事情的最佳方式 - 任何解决方案都适合我。

int width = 100;
int height = 100;

using (UIImage image = UIImage.FromFile(filePath))
{
    CGImage cgimage = image.CGImage;
    CGImageAlphaInfo alphaInfo = cgimage.AlphaInfo;

    if (alphaInfo == CGImageAlphaInfo.None)
        alphaInfo = CGImageAlphaInfo.NoneSkipLast;

    CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
        width,
        height,
        cgimage.BitsPerComponent,
        4 * width,
        cgimage.ColorSpace,
        alphaInfo);

    context.DrawImage(new RectangleF(0, 0, width, height), cgimage);

    /*
    Not sure how to convert this part:

    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);
    */
}

最佳答案

在即将到来的 MonoTouch 中我们将有一个缩放方法,这是它在 UIImage.cs 中的实现:

    public UIImage Scale (SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }

调整为在 MonoTouch 之外重复使用:

    public static UIImage Scale (UIImage source, SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), source.CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }

关于objective-c - 在 Monotouch 中调整大小并将图像保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2417969/

相关文章:

Jquery,如何围绕他的中心调整图像的大小

cocoa - 框架和边界(调整大小)-Cocoa

ios - 我有一个没有背景的 png 文件,如何在 iOS 中为该图像创建清晰的彩色背景?

javascript - 在不影响定位的情况下在普通 JavaScript 中调整表格大小

ios - xcode 5 构建比 xcode 6 构建更重

ios - 如何延迟由 dispatch_after 排队的 block 的执行?

java - J2ObjC:如何翻译自己的类型

ios - swift 4 : UIImage from URL

ios - 在 RubyMotion 中捕获 UIView

Swift 无法识别 Objective-C 枚举