UWP:将图像裁剪为圆形

时间:2019-07-27 14:32:45

标签: image-processing uwp

在UWP中,如何将图像(存储为字节[])裁剪为圆形。 需要明确的是-我不需要用户界面中的内容-我需要裁剪实际图像。 该过程或多或少如下(我认为):

  • 将byte []转换为UWP图像结构(BitmapDecoder?)
  • 将图像从中心裁剪为正方形
  • 剪切正方形图像的边界以形成一个圆

2 个答案:

答案 0 :(得分:2)

除了ImageSharp外,UWP社区工具包还提供了一些有关使用rect或circle解决图像裁剪的示例代码: https://github.com/windows-toolkit/WindowsCommunityToolkit/blob/master/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Helpers.cs

答案 1 :(得分:0)

您可以使用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);
}