简体   繁体   中英

How to clear the fill of a rectangle in C#?

How can I clear the fill of a rectangle? I only want to keep the border.

g.FillRectangle(Brushes.Transparent, x, y, w, h);

Didn't work, neither did aRGB with alpha, I want to delete the fill so there's only the border left.

So what you want is

g.DrawRectangle(Pens.Black,x,y,w,h);

I think

EDIT: due to a change in the OP requirements this is not exactly the answer he wants, though it is not incorrect, therefore I choose to leave it here, for now.

you must set new clip for your graphics after set clip clear it, then restore clip to normal.

g.SetClip(new Rectangle(x,y,w,h), CombineMode.Replace);
g.Clear(Color.Transparent);

Ok so you are after a selection tool, you might have wanted to tell us that in the first place.

Create a new windows form application.

in the form events use mousedown, mouseup and mousemove

public Point MouseXY = new Point(0, 0);

private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        MouseXY = e.Location;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            int width = e.Location.X - MouseXY.X;
            int height = e.Location.Y-MouseXY.Y;
            this.Refresh();
            CreateGraphics().DrawRectangle(Pens.Blue, new Rectangle(MouseXY, new Size(width,height)));

        }
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        this.Refresh();
    }

This code is not perfect and I don't pretend it is. What this will do is draw a blue rectangle that starts where you click and follows your mouse. It does not draw a negative rectangle, you would have to determine whether your mouse is currently to the left or up from your starting point then draw the rectangle accordingly, but I think you can figure that out on your own. as well the rectangle is not persistent, though I do not believe you would want it to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM