Search code examples
c#wpfcursor

Draw custom crosshair cursor only draws half of the cursor


I'm trying to draw a custom crosshair cursor.

This is my function to create the "cross cursor".

The problem is that it only draw the positive coordinates. So I get the half side of the cross.

enter image description here

So the red in this cross isn't visible when I draw it. A solution would be to make the cross all with positive coordinates but I don't want this.

Any solutions?

private Cursor crossCursor(System.Drawing.Pen pen, int x, int y)
{
    var pic = new Bitmap(x, y);
    var gr = Graphics.FromImage(pic);

    //gr.Clip = new Region(new RectangleF(-x / 2, -y / 2, x, y));

    var pathX = new GraphicsPath();
    var pathY = new GraphicsPath();
    pathY.AddLine(new Point(0, -y), new Point(0, y));
    pathX.AddLine(new Point(-x, 0), new Point(x, 0));
    gr.DrawPath(pen, pathX);
    gr.DrawPath(pen, pathY);

    var stream = new MemoryStream();
    Icon.FromHandle(pic.GetHicon()).Save(stream);

    // Convert saved file into .cur format
    stream.Seek(2, SeekOrigin.Begin);
    stream.WriteByte(2);
    stream.Seek(10, SeekOrigin.Begin);
    stream.Seek(0, SeekOrigin.Begin);

    // Construct Cursor
    return new Cursor(stream);
}

Solution

  • If the parameters x and y are, say, 10 each, you would create a bitmap of 10x10 in your code.

    So this line:

    pathY.AddLine(new Point(0, -y), new Point(0, y));
    

    Translates to:

    pathY.AddLine(new Point(0, -10), new Point(0, 10));
    

    The point (0,-10) lies outside of your bitmap and therefore will be invisible.

    There's no way you can draw inside the bitmap and show everything if you insist on using negative values...