我想检测我自定义创建区域的鼠标点击。
1)我试过这个代码与矩形,它工作,但有字符串,它没有
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);
}
这是第2部分
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (reg.IsVisible(e.Location))
{
MessageBox.Show("aaaa");
}
}
它没有显示消息框。 :)
编辑:这是我的Paint事件,看看我的字符串在哪里
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString("TEXT", new Font("Arial", 20), Brushes.Yellow, 300,100 );
}
最基本的错误是错字:有一次你在y = 10
画画,另一次画在y = 100
。
但还有另一个问题根本不是那么明显:
加
e.Graphics.FillPath(Brushes.Firebrick, gp);
到Paint
事件,你会看到它:字体有相当大的不同。
这是因为当向GraphicsPath
添加文本时,它使用的是与Graphics.DrawString
不同的比例(称为'emSize'),它使用'Point'。
要适应你可以使用这个:
float fontsize = 20.0f;
using (Graphics g = panel1.CreateGraphics()) fontsize *= g.DpiY / 72f;
现在你可以建立GraphicsPath
,最好用正确的坐标..:
gp.AddString("TEXT", new FontFamily("Arial"), 0, fontsize,
new Point(300, 100), StringFormat.GenericDefault);