我知道这篇文章很老了,但还是感谢你的帖子——它让我不再尝试使用比例来绘制图像。如果有人需要,我在这里分享一个扩展类。它可以让你像这样调整图像大小:
UIImage imgNew = img.Fit(40.0f, 40.0f);
我不需要适合的选项,但很容易扩展以支持填充。
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。
希望这能为某人节省一些时间。
干杯