我知道这很老了,但是感谢那篇文章-它使我从尝试使用比例尺重定向到绘制图像。万一对任何人都有利,我做了一个扩展类,我将在这里进行介绍。它允许您调整图像的大小,如下所示:
UIImage imgNew = img.Fit(40.0f, 40.0f);
我不需要合适的选项,但可以轻松扩展它以支持Fill。
using CoreGraphics;
using System;
using UIKit;
namespace SomeApp.iOS.Extensions
{
public static class UIImageExtensions
{
public static CGSize Fit(this CGSize sizeImage,
CGSize sizeTarget)
{
CGSize ret;
float fw;
float fh;
float f;
fw = (float) (sizeTarget.Width / sizeImage.Width);
fh = (float) (sizeTarget.Height / sizeImage.Height);
f = Math.Min(fw, fh);
ret = new CGSize
{
Width = sizeImage.Width * f,
Height = sizeImage.Height * f
};
return ret;
}
public static UIImage Fit(this UIImage image,
float width,
float height,
bool opaque = false,
float scale = 1.0f)
{
UIImage ret;
ret = image.Fit(new CGSize(width, height),
opaque,
scale);
return ret;
}
public static UIImage Fit(this UIImage image,
CGSize sizeTarget,
bool opaque = false,
float scale = 1.0f)
{
CGSize sizeNewImage;
CGSize size;
UIImage ret;
size = image.Size;
sizeNewImage = size.Fit(sizeTarget);
UIGraphics.BeginImageContextWithOptions(sizeNewImage,
opaque,
1.0f);
using (CGContext context = UIGraphics.GetCurrentContext())
{
context.ScaleCTM(1, -1);
context.TranslateCTM(0, -sizeNewImage.Height);
context.DrawImage(new CGRect(CGPoint.Empty, sizeNewImage),
image.CGImage);
ret = UIGraphics.GetImageFromCurrentImageContext();
}
UIGraphics.EndImageContext();
return ret;
}
}
}
按照上面的文章,它为图像启动了一个新的上下文,然后为该图像找出纵横比,然后绘制到图像中。如果您还没有完成任何Swift xcode开发时间,那么UIGraphics对于我使用的大多数系统都会有些落后,但还不错。一个问题是,默认情况下,位图从下至上绘制。为了解决这个问题,
context.ScaleCTM(1, -1);
context.TranslateCTM(0, -sizeNewImage.Height);
将图形的方向更改为更常见的左上角到右下角...,但是随后还需要移动原点,因此也需要移动TranslateCTM。
希望它可以节省一些时间。
干杯