我知道这已经很老了,但感谢那篇文章——它让我不再尝试使用比例来绘制图像。万一它对任何人都有好处,我做了一个扩展类,我会放在这里。它允许您像这样调整图像的大小:
UIImage imgNew = img.Fit(40.0f, 40.0f);
我不需要 fit 选项,但它也可以轻松扩展以支持 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。
希望它可以节省一些时间。
干杯