Introduction
You may encounter cases where you want to print on an image (from Photoshop or Word) template or
paper template etc. Like in an image map in HTML you have to maintain the position and size of some some shapes to draw some text.
For simplicity I use rectangle shape only in this example.
The project has these key points:
- Draw a simple shape (Rectangle) and re-position it.
- Save shape (Rectangle) position.
- Print using
PrintDocument
object - Use the saved positions in the printing demo.
Using the code
The key point in drawing and re-position is to maintain the three events of
the mouse: Mouse-down, Mouse-move, Mouse-up of the PictureBox
. In Mouse-down, we can determine if the action is painting,
drawing rectangle, or moving it.
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
foreach (string RectName in allRect.Keys)
{
Rectangle r;
allRect.TryGetValue(RectName, out r);
if (r.Contains(new Point(e.X, e.Y)))
{
movingRect = r;
moveRect = true;
break;
}
}
this.StartPoint = new Point(e.X, e.Y);
if (moveRect)
{
paint = false;
}
else
{
paint = true;
}
}
We check if the current position of the mouse is contained in some area of one of the shapes, otherwise we draw
a new shape.
In Mouse-move, we make the action of moving in case of re-positioning or draw the shape:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Point mouseDownLocation = new Point(e.X, e.Y);
label1.Text = "X pos:" + mouseDownLocation.X + " , Y pos:" + mouseDownLocation.Y;
if (paint)
{
if (paint)
{
EndPoint = mouseDownLocation;
}
}
else if(moveRect)
{
int leftDiff = mouseDownLocation.X-StartPoint.X;
int TopDiff = mouseDownLocation.Y-StartPoint.Y;
string tagetKey = "";
foreach (string RectName in allRect.Keys)
{
Rectangle r;
allRect.TryGetValue(RectName, out r);
if (r.Contains(new Point(e.X, e.Y)))
{
tagetKey = RectName;
break;
}
}
Rectangle t ;
allRect.TryGetValue(tagetKey, out t );
t.X =( ((t.Left+leftDiff)>=0)?(t.Left+leftDiff):t.Left-leftDiff);
t.Y = (((t.Top + TopDiff) >= 0) ? (t.Top + TopDiff) : 0);
allRect.Remove(tagetKey);
allRect.Add(tagetKey,t );
StartPoint = mouseDownLocation;
}
pictureBox1.Refresh();
}
Mouse-up: the end of operation and save the final position in a Dictionary
and then
ask the user for the name of the shape:
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
paint = false;
if (!moveRect)
{
this.EndPoint = new Point(e.X, e.Y);
string entryName =
InputMessageBox.ShowDialog("Enter EntryName", "Entry Name Dialog");
if (entryName != "")
{
allRect.Add(
entryName, new Rectangle(((StartPoint.X < EndPoint.X) ? StartPoint.X : EndPoint.X),
((StartPoint.Y < EndPoint.Y) ? StartPoint.Y : EndPoint.Y),
((StartPoint.X > EndPoint.X) ? StartPoint.X - EndPoint.X : EndPoint.X - StartPoint.X),
((StartPoint.Y > EndPoint.Y) ? StartPoint.Y - EndPoint.Y : EndPoint.Y - StartPoint.Y)
));
}
this.EndPoint = StartPoint;
}
else
{
moveRect = false;
}
pictureBox1.Refresh();
}