개발/C#

[이미지] C# Picturebox 내에서 이미지 움직이기

FA1976 2018. 2. 7. 13:25

picture 박스보다 큰 이미지를 Picture 박스에 이미지를 불러온뒤 움직이기


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;


namespace MoveImageOnPictrueBox

{

    public partial class Form1 : Form

    {

        private bool IsClicked = false;

        private Bitmap bm;

        private Point recLoc;

        private Point choosingPoint;


        public Form1()

        {

            InitializeComponent();

        }


        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)

        {

            bm = new Bitmap(openFileDialog1.FileName);


            pictureBox1.Image = bm;

           

        }




        private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.InitialDirectory = Application.StartupPath;

            openFileDialog1.ShowDialog();

        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            if(pictureBox1.Image != null)

            {

                pictureBox1.Image.Dispose();

            }

        }


        private void pictureBox1_Paint(object sender, PaintEventArgs e)

        {

            if (IsClicked)

            {

                e.Graphics.Clear(Color.White);

                e.Graphics.DrawImage(bm, recLoc);

            }

        }


        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)

        {

            IsClicked = true;

            choosingPoint.X = e.X;

            choosingPoint.Y = e.Y;  

        }


        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)

        {

            if (IsClicked)

            {

                recLoc.X = recLoc.X + e.X - choosingPoint.X;

                recLoc.Y = recLoc.Y + e.Y - choosingPoint.Y;

                choosingPoint = e.Location;

                pictureBox1.Invalidate();

            }

        }


        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)

        {

            IsClicked = false;

        }


    }

}



MoveImageOnPictrueBox.zip