we can drag image inside the pictureBox.
Please follow the steps one by one.
- Place PictureBox in the form.
- Set the following Properties for the PictureBox
- BackColor -> Transparent
- BackgroundImage->Give the image path of PNG file from your system.
- BackgroundImageLayout ->Stretch
- SizeMode -> Autosize
contains details about Image,Width,Height and Location.
class DraggableImage
{
public Bitmap img;
public Point Loc;
public int Width;
public int Height;
public DraggableImage(Bitmap bmpImg,Point loc)
{
this.img = bmpImg;
this.Loc = loc;
this.Width = bmpImg.Width;
this.Height = bmpImg.Height;
}
}
4. In the Form use the following coding,
public partial class Form1 : Form
{
DraggableImage di = new DraggableImage(Properties.Resources._1, new Point(0, 0));
int mx, my;
[Category("Property")]
[Description("Get and Set the draggable Image")]
public Bitmap DragImage
{
get { return di.img; }
set { di.img = value; Refresh(); }
}
public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
}
private void Form1_Load(object sender, EventArgs e)
{
this.DragImage =(Bitmap)QDOES.ImageOptimizer.ResizeToMaxSize(di.img,
pictureBox1.Width, pictureBox1.Height, 96, 96);
di.Loc = new Point(pictureBox1.Left,pictureBox1.Top);
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
this.pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new MouseEventHandler(pictureBox1_MouseMove);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
di.Loc.X = e.X - mx + di.Loc.X;
di.Loc.Y = e.Y - my + di.Loc.Y;
mx = e.X;
my = e.Y;
Refresh();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mx = e.X;
my = e.Y;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (di != null)
{
e.Graphics.DrawImage(di.img, di.Loc);
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
di.Loc.X = e.X - mx + di.Loc.X;
di.Loc.Y = e.Y - my + di.Loc.Y;
mx = e.X;
my = e.Y;
Refresh();
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mx = e.X;
my = e.Y;
}
}
No comments:
Post a Comment