winform加载svg图,然后我想点击svg图上一个元素获取这个元素的id,怎么实现呢,以下是我原来的思路是:点击一个元素判断有没有超过范围,然后获取id,但是 if (element is SvgRectangle rect){}这个判断中rect要是为null,有没有好的解决方法
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadSvg("D:\\11122.svg");
//changElementColor();
}
SvgDocument svgDocument;
//加载svg图
private void LoadSvg(string filePath)
{
svgDocument = SvgDocument.Open(filePath);
// 将 SVG 转换为 Bitmap
var bitmap = svgDocument.Draw();
pictureBox1.Image = bitmap;
//pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox1.MouseClick += PictureBox_MouseClick;
}
//点击事件
private void PictureBox_MouseClick(object sender, MouseEventArgs e)
{
foreach (var element in svgDocument.Children)
{
if (element is SvgVisualElement visualElement)
{
Console.WriteLine(element.ID);
// 简单判断点击是否在元素的矩形范围内
if (IsPointInsideElement(e.Location, visualElement))
{
MessageBox.Show($"点击了元素: {visualElement.ID}");
}
}
}
}
//判断图元范围
private bool IsPointInsideElement(Point point, SvgVisualElement element)
{
// 判断点击点是否在图元范围内(根据元素的矩形范围来判断)
if (element is SvgRectangle rect)
{
PointF pointF = new PointF(point.X, point.Y);
var rectBounds = new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
Console.WriteLine("element:" + element.ID + " RectangleF===" + rect.X + "==" + rect.Y + "==" + rect.Width + "==" + rect.Height);
Console.WriteLine("element:" + element.ID + " pointF======" + pointF.X + "==" + pointF.Y);
return rectBounds.Contains(pointF);
}
return false;
}