Search code examples
javac#windowsvisual-studiopaint

C# Windows Form Picture Box Drawing With Mouse


EDIT: Drawing a 4 pointed star does work now with this code but i don't really know WHY this works, AND if i divide by the same number for x & y it just gives me a diamond??? 3 & 7 seem to be the best values too and i have no idea why...

  public AP4Star() { }

    public AP4Star(int x1, int y1, int x2, int y2, Color c, bool solid, float penW) : base(x1, y1, x2, y2, c, solid, penW) { }

    public override void Draw(Graphics g)
    {
        float xDisplacement = Math.Abs(getX1() - getX2());
        float yDisplacement = Math.Abs(getY1() - getY2());

        PointF top = new PointF((getX1() + getX2()) / 2, Math.Min(getY2(), getY1()));
        PointF bottom = new PointF(top.X, Math.Max(getY2(), getY1()));
        PointF left = new PointF(Math.Min(getX2(), getX1()), (top.Y + bottom.Y) / 2);
        PointF right = new PointF(Math.Max(getX2(), getX1()), left.Y);

        PointF mtr = new PointF(right.X - xDisplacement / 3, right.Y - yDisplacement / 7);
        PointF mbr = new PointF(right.X - xDisplacement / 3, right.Y + yDisplacement / 7);
        PointF mbl = new PointF(left.X + xDisplacement / 3, left.Y + yDisplacement / 7);
        PointF mtl = new PointF(left.X + xDisplacement / 3, left.Y - yDisplacement / 7);





        PointF[] fourStar = { top,mtr, right, mbr, bottom, mbl, left, mtl };

        g.DrawPolygon(new Pen(getColor(), getPenWidth()), fourStar);

That code produce a pretty good pointy star but i feel like i am still doing this wrong... : result


Solution

  • I don't think this is really a coding question, it's more of a logic question. But here's how I'd solve it:

    Start by zero-indexing all of your points. Assuming all of your points are equidistant from zero, that means n = 10 gives you four points like the following for your initial diamond:

    p1: { x = 0, y = 10}
    p2: { x = 10, y = 0}
    p3: { x = 0, y = -10}
    p4: { x = -10, y = 0}
    

    Now just add each of those points with a new point that has n / 4 (if it was n / 2, it'd be a straight line. So n / 4 ... or anything greater than 2, should get you a pointy star). So if we use n/4, you get the following eight points:

    p1: { x = 0, y = 10}
    p2: { x = 2.5, y = 2.5}
    p3: { x = 10, y = 0}
    p4: { x = 2.5, y = -2.5}
    p5: { x = 0, y = -10}
    p6: { x = -2.5, y = -2.5
    p7: { x = -10, y = 0}
    p8: { x = -2.5, y = 2.5}
    

    Now just draw a line between each of those points and you should have your pointy star. I hope that's helpful!