Help with PictureBox and graphics

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

I am making a program that needs to put a copy of a certain small image
wherever the user clicks with the mouse. I am using a pictureBox as my main
area (although I can change this if necessary). How can I paste my image in
various places on the pictureBox?

I thought it might be something like this...?

PasteImage(x,y);
PasteImage(x+100,y+100);

Thanks!!
 
Here's one idea on how this could be done.

Store the Points where the user clicked in some type of list (ArrayList, for
example) and then paint the images from within a Paint event handler, or
OnPaint override for a custom control. Using a Panel as the canvas, it would
go something like this.

private ArrayList imageLocations = new ArrayList();
private Image image = Image.FromFile(@"C:\Image.bmp");

private void panel1_Click(object sender, System.EventArgs e)
{
Point point = this.panel1.PointToClient(Control.MousePosition);
this.imageLocations.Add(point);
this.panel1.Invalidate(new Rectangle(point.X, point.Y, this.image.Width,
this.image.Height));
}

private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
foreach (Point point in this.imageLocations)
{
e.Graphics.DrawImage(this.image, point.X, point.Y);
}
}

The Panel area can be reset using the following code.

this.imageLocations.Clear();
this.panel1.Invalidate();
 
Store the Points where the user clicked in some type of list (ArrayList,
for
example) and then paint the images from within a Paint event handler, or
OnPaint override for a custom control. Using a Panel as the canvas, it
would
go something like this.

Would this method add the image to the panel as a graphic? Or would I have
to make the app remember where each of the points are for the next time it
pulls up the panel?
 
The ArrayList is storing the Points and everytime the Panel paints its
entire surface it would need to paint the images at those indicated
locations. If you're looking to save the image on the Panel then you could
do something similar to the following.

using System.Drawing.Imaging;

private Bitmap bmp = null;

public Form1()
{
InitializeComponent();
SizeBitmap();
}

private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
Graphics graphic = Graphics.FromImage(this.bmp);
graphic.Clear(this.panel1.BackColor);
foreach (Point point in this.imageLocations)
{
graphic.DrawImage(this.image, point.X, point.Y);
}
e.Graphics.DrawImage(this.bmp, 0, 0);
graphic.Dispose();
}

private void panel1_Resize(object sender, System.EventArgs e)
{
SizeBitmap();
}

private void SizeBitmap()
{
if (this.bmp != null)
{
this.bmp.Dispose();
}
this.bmp = new Bitmap(this.panel1.Width, this.panel1.Height);
}

private void SaveBitmap()
{
if (this.bmp != null)
{
this.bmp.Save(@"C:\SavedImage.gif", ImageFormat.Gif);
}
}

Now the images are being added to the Panel as one graphic.
 
Back
Top