// // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // namespace ImageSharp.Drawing.Processors { using System; using System.Numerics; using System.Threading.Tasks; using Drawing; using ImageSharp.Processing; using Shapes; using Rectangle = ImageSharp.Rectangle; /// /// Usinf a brsuh and a shape fills shape with contents of brush the /// /// The type of the color. /// public class FillShapeProcessor : ImageProcessor where TColor : struct, IPackedPixel, IEquatable { private const float AntialiasFactor = 1f; private const int DrawPadding = 1; private readonly IBrush fillColor; private readonly IShape poly; private readonly GraphicsOptions options; /// /// Initializes a new instance of the class. /// /// The brush. /// The shape. /// The graphics options. public FillShapeProcessor(IBrush brush, IShape shape, GraphicsOptions options) { this.poly = shape; this.fillColor = brush; this.options = options; } /// protected override void OnApply(ImageBase source, Rectangle sourceRectangle) { Rectangle rect = RectangleF.Ceiling(this.poly.Bounds); // rounds the points out away from the center int polyStartY = rect.Y - DrawPadding; int polyEndY = rect.Bottom + DrawPadding; int startX = rect.X - DrawPadding; int endX = rect.Right + DrawPadding; int minX = Math.Max(sourceRectangle.Left, startX); int maxX = Math.Min(sourceRectangle.Right - 1, endX); int minY = Math.Max(sourceRectangle.Top, polyStartY); int maxY = Math.Min(sourceRectangle.Bottom - 1, polyEndY); // Align start/end positions. minX = Math.Max(0, minX); maxX = Math.Min(source.Width, maxX); minY = Math.Max(0, minY); maxY = Math.Min(source.Height, maxY); // Reset offset if necessary. if (minX > 0) { startX = 0; } if (minY > 0) { polyStartY = 0; } using (PixelAccessor sourcePixels = source.Lock()) using (BrushApplicator applicator = this.fillColor.CreateApplicator(sourcePixels, rect)) { Parallel.For( minY, maxY, this.ParallelOptions, y => { int offsetY = y - polyStartY; Vector2 currentPoint = default(Vector2); for (int x = minX; x < maxX; x++) { int offsetX = x - startX; currentPoint.X = offsetX; currentPoint.Y = offsetY; float dist = this.poly.Distance(currentPoint); float opacity = this.Opacity(dist); if (opacity > Constants.Epsilon) { Vector4 backgroundVector = sourcePixels[offsetX, offsetY].ToVector4(); Vector4 sourceVector = applicator.GetColor(currentPoint).ToVector4(); Vector4 finalColor = Vector4BlendTransforms.PremultipliedLerp(backgroundVector, sourceVector, opacity); finalColor.W = backgroundVector.W; TColor packed = default(TColor); packed.PackFromVector4(finalColor); sourcePixels[offsetX, offsetY] = packed; } } }); } } /// /// Returns the correct alpha value for the given distance. /// /// /// The distance. /// /// /// The . /// private float Opacity(float distance) { if (distance <= 0) { return 1; } if (this.options.Antialias && distance < AntialiasFactor) { return 1 - (distance / AntialiasFactor); } return 0; } } }