Coder Social home page Coder Social logo

sixlabors / shapes Goto Github PK

View Code? Open in Web Editor NEW
101.0 18.0 28.0 910 KB

:triangular_ruler: Net standard geometry/shape manipulation library, can be used to merge / split shapes

Home Page: https://sixlabors.com/projects/shapes

License: Other

C# 98.88% Batchfile 0.32% PowerShell 0.80%
shape polygon cross-platform bezier path netstandard

shapes's Introduction

The contents of this repo have been intergated directly into https://github.com/SixLabors/ImageSharp.Drawing


SixLabors.Shapes
SixLabors.Shapes

Build status codecov GitHub license

Join the chat at https://gitter.im/SixLabors/Shapes GitHub issues GitHub stars GitHub forks

SixLabors.Shapes is a new cross-platform 2D polygon manipulation API.

Installation

Pre-release downloads

At present the code is pre-release we have initial pre-releases availible on nuget.

We also have a MyGet package repository - for bleeding-edge / development NuGet releases.

Manual build

If you prefer, you can compile SixLabors.Shapes yourself (please do and help!), you'll need:

To clone it locally click the "Clone in Windows" button above or run the following git commands.

git clone https://github.com/SixLabors/Shapes.git

Features

  • Point in Polygon
  • Line Intersections
  • Complex Polygons
  • Simple polygon clipping
  • Regular Polygons (triangles, squares, pentagons etc, any number of sides)
  • Ellipses (and therfore circles)
  • Shape Builder api - for creating shapes declaratively
  • Polygons
    • With Linear line segments
    • With Beziear curve line segments
    • Mixture of both Linear & bezier segments
  • Paths
    • With Linear line segments
    • With Bezier curve line segments
    • Mixture of both Linear & bezier segments

How can you help?

Please... Spread the word, contribute algorithms, submit performance improvements, unit tests.

Projects using SixLabors.Shapes

The SixLabors.Shapes Team

Lead

Core Team

shapes's People

Contributors

antonfirsov avatar billbogaiv avatar dlemstra avatar gitter-badger avatar iamcarbon avatar jimbobsquarepants avatar marymajesty avatar nilzen avatar sa-exe avatar tocsoft avatar woutware avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shapes's Issues

Add regular multisided polygons

Add a regular multi sided polygon that takes;

  1. a number of sides
  2. a center point
  3. an angle of rotation
  4. and a distance from vertex

we drop some intersections in large complex composite shapes (text)

cross posted from SixLabors/ImageSharp#572 to enable investigation
generate a large amount of text using some text using this code as a guide

TextOptions = new TextGraphicsOptions
            {
                Antialias = true,
                ApplyKerning = true, 
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Left,
                WrapTextWidth = PageSize.Width
            };


 using (Image<Rgba32> img = new Image<Rgba32>(PageSize.Width, PageSize.Height))
            {
                img.MetaData.HorizontalResolution = 300;
                img.MetaData.VerticalResolution = 300;

                img.Mutate(x =>
                    x.Fill(Rgba32.White)
                        .DrawText(TextOptions, text, Font, Rgba32.Black, new PointF(10, 5))

                );
                img.Save($"output/0.png");   

we are dropping more and more intersections over the render (could this be due to Vector2 jitting issues?)

merge the IPath and IShape interfaces into a single structure

IPath should have

  • Rectangle Bounds { get; } bounds enclosing the path
  • PointInfo Distance(Vector2 point) distance from and along the path
  • IPath Transform(Matrix3x2 matrix) applies the matrix transform to the path.
  • int MaxIntersections { get; } Gets the maximum number intersections that a shape can have when testing a line.
  • IsClosed details weather the path is closed or open
  • bool Contains(Vector2 point); returns true if the point is contained within the closed version of this path
  • int FindIntersections(Vector2 start, Vector2 end, Vector2[] buffer, int count, int offset); populates the buffer with all the point that intersect the line
  • IPath AsClosedPath() if this is an open path closes it and returns that, otherwise it returns itself
  • ImmutableArray<SimplePath> Flatten() a collection of simple paths making up this potentially complex one

Add new SimplePath struct

  • ImmutableArray<Vector2> Points { get; }
  • bool IsClosed { get; }

drop IShape as IPath will cover the requirements

Return location and angle of point along a path

Add API that takes in a distance along a path and returns the location and angle of intersection.

For complex paths the distance flows from the end of one path into the next one in the order they where provided.

Once the complete length has been reached it will start again from the start.

GenerateOutline as used in ImageSharp produces wrong results with self-intersecting lines

I am not sure if this bug is in the way ImageSharp uses GenerateOutline or if this is a bug in this library. I'm posting it here first, will gladly move it to ImageSharp if the problem is on that side.

I have code that draws lines that may intersect themselves in the exact same point. In this case it seems that GenerateOutline assumes it's a closed path and stops drawing anything after this point.

Here's the simplest code to demonstrate the problem:

using ImageSharp;
using ImageSharp.Drawing.Pens;
using ImageSharp.PixelFormats;
using System.IO;

namespace ConsoleApp1
{
	class Program
	{
		static void Main(string[] args)
		{
			using (var image = new Image<Argb32>(256, 256))
			{
				image.Fill(new Argb32(0, 0, 0));

				var pen1 = new Pen<Argb32>(new Argb32(255, 0, 0), 5f);
				var line1 = new Vector2[] { new Vector2(117f, 199f), new Vector2(31f, 210f), new Vector2(35f, 191f), new Vector2(117f, 199f), new Vector2(2f, 9f) };

				image.DrawLines(pen1, line1);

				var pen2 = new Pen<Argb32>(new Argb32(0, 255, 0), 5f);
				var line2 = new Vector2[] { new Vector2(217f, 199f), new Vector2(131f, 210f), new Vector2(135f, 191f), new Vector2(217f, 199.001f), new Vector2(2f, 9f) };

				image.DrawLines(pen2, line2);

				image.SaveAsPng(File.OpenWrite(@"isharp.png"));
			}
		}
	}
}

The result is this:

isharp

The red line that has identical points will stop drawing at that point but a small difference will allow it to continue.

The first line generates this kind of outline shape (first of the two):

sloutline1

The second one:

sloutline2

As said I'm not sure if GenerateOutline is supposed to work like this, in which case ImageSharp needs to fix this, or if it's a bug in this library. If there's any other information needed I'll be happy to help.

Running on SixLabors.Shapes 0.1.0-alpha0016, ImageSharp 1.0.0-alpha9-00112, ImageSharp.Drawing 1.0.0-alpha9-00107

Pencil width is always 2 pixels.

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

Description

I need to create a rectangle of 10 x 10 pixels ,width 1 pixel, but I can only obtain width of 2 pixels.

Obtained result

obtenido

Desired result

deseado

Steps to Reproduce

            var width = 32;
            var height = 32;            
            var name = "Rectangle";
            
            using (Image<Rgba32> image = new Image<Rgba32>(width, height))
            {
                Rectangle rect = new Rectangle(0, 0, 10, 10);
                Pen<Rgba32> pen = new Pen<Rgba32>(Rgba32.White, 1f);
                image.Mutate(i => i.Draw(pen, rect));                
                image.Save(name+".bmp");
            }

System Configuration

  • ImageSharp version: 1.0.0-beta0004
  • Other ImageSharp packages and versions: SixLabors.ImageSharp.Drawing 1.0.0-beta0004
  • Environment (Operating system, version and so on): Win 10 Pro build 17134
  • .NET Framework version:.Net Core 2.0
  • Additional information:

Missing clipped corner from FindIntersections(...)

When finding intersections and you just clip a corner then you should have 2 intersection points, 1 for hitting the corner and a second for immediately exiting it again.

We want 2 hits for people doing intersection counting while traversing the line.

Example of this is ImageSharp using it to fill pixels inside/outide the polygo and with 1 hit it will flip the remaining points along the line to inside/outside incorrectly and with 0 hits the point wont get rendered at all.

Path outlining (with pattern support)

Add a new extension method to IPath that will walk along a series of path segments and generate a new IPath representing to outline of the source path.

If a pattern is supplied we will generate 2 alternating IPaths.

Provide options to outline for specifying the joint types

The underlying clipping outlining library we are using provider support for multiple joint types.

We currently hard code the used joint type and end type used.
Update the GenerateOutline extension method to accept an options struct

struct OutlineOptions{
    /// the thickness of the outline.
    float Width { get; set; } = 1f; // 

    /// the patterns in multiples of the thinkness
    float[] Pattern { get; set;} = new []{ 1 } // no pattern

    /// if the first items in the pattern is on or off
    bool StartOff { get; set; } = false;

    /// the style of joint for the line
   JoinType JointType { get; set; } = JoinType.Square;

    /// the style for the end of the line (only applicable for open paths)
   EndType EndType  { get; set; } = EndType.OpenButt;
}

enum JoinType{
    Square, 
    Round, 
    Miter
}

enum EndType {
    OpenButt, 
    OpenSquare, 
    OpenRound 
}

This will allow for curves at joints and rounded ends.

Q: Use case of library

Hi,
very general questions: What would be a use case of your library? Say, I want do develop a diagram designer and the graphics core should be cross-platform. Would I use it then? If I have a WPF client how would I render those shapes? Then I need a piece of code translating your shapes into visuals of WPF? Would I have access to all the data needed to render those shapes in WPF? How would I do dragging, selecting etc? Your shapes don't support such things (MouseEvents).

Sorry, it's very confusing for me at the moment. Any help would be greatly appreciated,
Sven

TextBuilder does not exist in SixLabors.Shapes

Using 1.0.0-beta0008 and .NET Core 2.1 but unable to see TextBuilder in this namespace. Your code samples are referencing SixLabors.Shapes.TextBuilder. Just wondering what I'm doing wrong.

Incorrect Usage of RectangularPolygon(TopLeft, BottomRight) constructor in overload

/// <summary>
        /// Initializes a new instance of the <see cref="RectangularePolygon" /> class.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        public RectangularePolygon(float x, float y, float width, float height)
            : this(new PointF(x, y), new SizeF(width, height))
        {
        }

public RectangularePolygon(PointF location, SizeF size)
            : this(location, location + size)
        {
        }

I believe this is wrong. If you Use the overload correctly you should be passing in the top left corner as the location and new SizeF(width, height) should equate to the lower right hand corner however the overload location + size inverts your rectangle and makes the location the bottom left corner and the location + size becomes the top right corner. This ends up inverting all of the named corners in the rectangle and also messes with some other methods. To overcome this you have to pass in negative y values for the height of your rectangle to get the actual rectangle you wanted.

System.MissingMethodException

Hi,
when starting the example program I get following exception:

System.MissingMethodException: 'Method not found: 'SixLabors.Shapes.Rectangle SixLabors.Shapes.IPath.get_Bounds()'.'<

at
img.Fill(Rgba32.HotPink, s, new ImageSharp.GraphicsOptions(true));

Why does this even compile? Is there some reflection involved?
Thx,
Sven

No Rounded Corners - No Sharp Corners - Only a in between?

I'm currently writing a SVG parser which can convert SVG's to PNG's but I'm running into a few issues

ISSUE 1:
The corners of my rectangles aren't sharp but slightly rounded. Same counts for the other shapes. I expected them to be sharper than this. See followng images (Blue line at the bottom is element and haven't got it working yet!):
Generated
test
Original
shapes
https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Basic_Shapes

ISSUE 2/Feature Request:
As can be seen above, I haven't got the rounded corners working. Is this even possible?

missed edges for a set of shapes

the following ellipses miss hitting edges thusly making ImageSharp render badly

Y Scan line = 603 for

new ComplexPolygon(new SixLabors.Shapes.Ellipse(new Vector2(603), 161f), new SixLabors.Shapes.Ellipse(new Vector2(603), 61f))

Y Scan lines [579, 580, 583,587,590,594,597,598,601,605,608,609,612,616,619,623,625,626] for

new SixLabors.Shapes.Ellipse(new Vector2(603), 603f-60))

Y Scan line = 512 for

var center = new Vector2(603);
  var segmentRotationCenter = new Vector2(301.16968f, 301.16974f);
            var segment = new Polygon(new LinearLineSegment(new Vector2(230.54f, 361.0261f), new System.Numerics.Vector2(5.8641942f, 361.46031f)),
                new BezierLineSegment(new Vector2(5.8641942f, 361.46031f),
                new Vector2(-11.715693f, 259.54052f),
                new Vector2(24.441609f, 158.17478f),
                new Vector2(78.26f, 97.0461f))).Translate(center - segmentRotationCenter);

                float angle = 2 * ((float)Math.PI / 3);
                var s = segment.Transform(Matrix3x2.CreateRotation(angle, center));

Y Scan line = 694 for

var center = new Vector2(603);
  var segmentRotationCenter = new Vector2(301.16968f, 301.16974f);
            var segment = new Polygon(new LinearLineSegment(new Vector2(230.54f, 361.0261f), new System.Numerics.Vector2(5.8641942f, 361.46031f)),
                new BezierLineSegment(new Vector2(5.8641942f, 361.46031f),
                new Vector2(-11.715693f, 259.54052f),
                new Vector2(24.441609f, 158.17478f),
                new Vector2(78.26f, 97.0461f))).Translate(center - segmentRotationCenter);

                float angle = 5 * ((float)Math.PI / 3);
                var s = segment.Transform(Matrix3x2.CreateRotation(angle, center));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.