UWP:将图像裁剪为圆形
Posted
技术标签:
【中文标题】UWP:将图像裁剪为圆形【英文标题】:UWP: Crop an image to a circle 【发布时间】:2019-07-27 14:32:45 【问题描述】:在 UWP 中,如何将图像(存储为 byte[])裁剪为圆形。 需要明确的是——我在 UI 中不需要这个——我需要裁剪实际的图像。 这个过程或多或少的工作如下(我认为):
将 byte[] 转换为 UWP 图像构造 (BitmapDecoder
?)
将图像从中心裁剪成正方形
剪裁方形图像的边界以制作圆形
【问题讨论】:
【参考方案1】:除了 ImageSharp,UWP 社区工具包还提供了一些使用矩形或圆形解决图像裁剪的示例代码: https://github.com/windows-toolkit/WindowsCommunityToolkit/blob/master/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Helpers.cs
【讨论】:
【参考方案2】:您可以使用free open-source library ImageSharp
,它提供了圆形裁剪功能,甚至提供了一个具有此功能的工作示例。该库与 .NET Standard 1.3 兼容,因此它应该可以在您的 UWP 应用程序中正常工作。圆形作物样本也是here on GitHub。
代码的关键部分在这里:
// This method can be seen as an inline implementation of an `IImageProcessor`:
// (The combination of `IImageOperations.Apply()` + this could be replaced with an `IImageProcessor`)
public static void ApplyRoundedCorners(Image<Rgba32> img, float cornerRadius)
IPathCollection corners = BuildCorners(img.Width, img.Height, cornerRadius);
var graphicOptions = new GraphicsOptions(true)
AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background
;
// mutating in here as we already have a cloned original
// use any color (not Transparent), so the corners will be clipped
img.Mutate(x => x.Fill(graphicOptions, Rgba32.LimeGreen, corners));
public static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
// first create a square
var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);
// then cut out of the square a circle so we are left with a corner
IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));
// corner is now a corner shape positions top left
//lets make 3 more positioned correctly, we can do that by translating the orgional artound the center of the image
float rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1;
float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1;
// move it across the width of the image - the width of the shape
IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);
return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
【讨论】:
谢谢马丁!对于以下人员 - 这是一个将 byte[] 图像作为输入的代码的链接,并将裁剪的圆形图像作为 byte[] github.com/InquisitorJax/Xamarin-Forms-Syncfusion-Pdf/blob/…以上是关于UWP:将图像裁剪为圆形的主要内容,如果未能解决你的问题,请参考以下文章