I’m reading list of points from a json file and then draw the points on a file and then display the file with the drawn points. the problem is that if before loading i wad drawing points they will stay when loading. i need to clear the image file before drawing the points form the loading json. i’m not using paint event but Graphics for drawing on the image file.
the problem is how to clear the points from the image first before drawing the points form the loaded list in this method RedrawAnnotations.
method to load from json:
private void LoadPointsFromJson()
{
string filePath = Path.Combine(@"d:savedpoints", "points.json");
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
var pointsData = JsonConvert.DeserializeObject<dynamic>(json);
_points = JsonConvert.DeserializeObject<List<System.Drawing.Point>>(Convert.ToString(pointsData.PointsOnPictureBox));
_pointsOnImage = JsonConvert.DeserializeObject<List<System.Drawing.Point>>(Convert.ToString(pointsData.PointsOnImage));
UpdatePointsOnUI();
}
}
method to update the ui like pictureboxes and listboxes:
private void UpdatePointsOnUI()
{
listBoxPointsOnPicturebox.Items.Clear();
listBoxPointsOnImage.Items.Clear();
foreach (var point in _points)
{
listBoxPointsOnPicturebox.Items.Add($"Point {{X={point.X}, Y={point.Y}}}");
}
foreach (var point in _pointsOnImage)
{
listBoxPointsOnImage.Items.Add($"Point {{X={point.X}, Y={point.Y}}}");
}
pictureBoxPoints.Invalidate();
// Redraw annotations on the image if necessary
RedrawAnnotations();
}
method to draw the loaded list of points on the image file:
private void RedrawAnnotations()
{
if (pictureBoxImageFilePoints.Image != null)
{
int rectSize = 10;
Bitmap imageClone = (Bitmap)pictureBoxImageFilePoints.Image.Clone();
using (Graphics g = Graphics.FromImage(imageClone))
{
foreach (var point in _pointsOnImage)
{
g.FillEllipse(Brushes.Red, new Rectangle(point.X - 5, point.Y - 5, 10, 10)); // Offset by 5 to center the ellipse
g.DrawRectangle(Pens.Red, new Rectangle(point.X - rectSize / 2, point.Y - rectSize / 2, rectSize, rectSize));
}
}
pictureBoxImageFilePoints.Image = imageClone;
}
}
loading button click event:
private void buttonLoad_Click(object sender, EventArgs e)
{
LoadPointsFromJson();
}