问题
I want to detect mouse click on my custom created region.
1) I ve tried this code with rectangle and it worked, but with string it doesnt
GraphicsPath gp = new GraphicsPath();
Region reg = new Region();
private void Form1_Load(object sender, EventArgs e)
{
gp.AddString("TEXT", new FontFamily("Arial"),0, 20.0f, new Point(300, 10), StringFormat.GenericDefault);
gp.Widen(Pens.AliceBlue);
reg = new Region(gp);
}
and here is the part2
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (reg.IsVisible(e.Location))
{
MessageBox.Show("aaaa");
}
}
It doesnt show the message box. :)
EDIT :here is my Paint event to see where my string is
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString("TEXT", new Font("Arial", 20), Brushes.Yellow, 300,100 );
}
回答1:
The most basic error is a typo: One time you draw at y = 10
, the other time at y = 100
.
But there is another issue which is not so obvious at all:
Add
e.Graphics.FillPath(Brushes.Firebrick, gp);
to the Paint
event and you'll see it: The fonts have quite a different size.
That is because when adding text to a GraphicsPath
it is using a different scale (called 'emSize') than Graphics.DrawString
does, which uses 'Point'.
To adapt you can use this:
float fontsize = 20.0f;
using (Graphics g = panel1.CreateGraphics()) fontsize *= g.DpiY / 72f;
Now you can build the GraphicsPath
, best with the correct coordinates..:
gp.AddString("TEXT", new FontFamily("Arial"), 0, fontsize,
new Point(300, 100), StringFormat.GenericDefault);
来源:https://stackoverflow.com/questions/52234681/c-sharp-winforms-region-isvisible