我正在使用 ImageSharp 在我的 UWP 应用程序中进行一些基本的图像编辑,我需要做的一件事是将图像裁剪为圆形(您可以假设图像已经是正方形)。
我找不到适用Clip
于其他任何矩形的 API,所以我想出了以下代码段:
// Image is an Image<Argb32> instance
image.Mutate(context =>
{
context.Apply(target =>
{
double half = target.Height / 2.0;
unsafe
{
fixed (Argb32* p = target.GetPixelSpan())
for (int i = 0; i < target.Height; i++)
for (int j = 0; j < target.Width; j++)
if (Math.Sqrt((half - i).Square() + (half - j).Square()) > half)
p[i * target.Width + j] = default;
}
});
});
注意:该Square
方法只是一个扩展,它接受 adouble
并返回其平方值。
现在,这工作正常,而且速度相当快,因为我正在处理足够小的图像(例如,每个轴 <= 250 像素)。height / 2
此代码段只是将位于以图像中心为中心的半径为 的圆之外的每个像素设置为透明像素。
我想知道是否没有另一种更直观的方法来做同样的事情,我只是错过了。
谢谢您的帮助!