Skip to content

Instantly share code, notes, and snippets.

@equinox2k
Last active October 9, 2019 06:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save equinox2k/ee2f9af656c25495ca0a18d1c30c8b6f to your computer and use it in GitHub Desktop.
Save equinox2k/ee2f9af656c25495ca0a18d1c30c8b6f to your computer and use it in GitHub Desktop.
RoundCornersProcessor for ImageSharp
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using SixLabors.Shapes;
namespace EQL.ImageSharp
{
public static class RoundCornersProcessor
{
public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerPercentX, float cornerPercentY)
{
Size size = ctx.GetCurrentSize();
IPathCollection corners = BuildCorners(size.Width, size.Height, cornerPercentX, cornerPercentY);
var graphicOptions = new GraphicsOptions(true)
{
AlphaCompositionMode = PixelAlphaCompositionMode.DestOut
};
return ctx.Fill(graphicOptions, Rgba32.Black, corners);
}
private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerPercentX, float cornerPercentY)
{
var cornerRadiusX = imageWidth * (cornerPercentX / 100.0f);
var cornerRadiusY = imageHeight * (cornerPercentY / 100.0f);
var rightOffset = imageWidth - cornerRadiusX;
var bottomOffset = imageHeight - cornerRadiusY;
var rect = new RectangularPolygon(0, 0, cornerRadiusX, cornerRadiusY);
IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadiusX, cornerRadiusY, cornerRadiusX * 2, cornerRadiusY * 2));
IPath cornerTopRight = rect.Clip(new EllipsePolygon(0, cornerRadiusY, cornerRadiusX * 2, cornerRadiusY * 2)).Translate(rightOffset, 0);
IPath cornerBottomLeft = rect.Clip(new EllipsePolygon(cornerRadiusX, 0, cornerRadiusX * 2, cornerRadiusY * 2)).Translate(0, bottomOffset);
IPath cornerBottomRight = rect.Clip(new EllipsePolygon(0, 0, cornerRadiusX * 2, cornerRadiusY * 2)).Translate(rightOffset, bottomOffset);
return new PathCollection(cornerTopLeft, cornerTopRight, cornerBottomLeft, cornerBottomRight);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment