当前位置:首页 > Windows程序 > 正文

C#实现图像的鼠标裁剪

2021-05-26 Windows程序

C#的图像裁剪很容易操作,这里给个实现的例子

关键是需要处理鼠标的事件和一些更新

实现鼠标移动的代码.注意更新不要全部重画,只有选择矩形部分重画

private void Form1_MouseMove(object sender, MouseEventArgs e)
        {

if (Track_move)
                endpoint = new Point(e.X, e.Y);
            else
            {
                return;
            }
            rect1 = new Rectangle(stpoint.X, stpoint.Y, endpoint.X - stpoint.X, endpoint.Y - stpoint.Y);

Rectangle tempr = new Rectangle(rect1.X, rect1.Y, rect1.Width + 2, rect1.Height + 2);
            this.Invalidate(tempr);
        }

选择结束的处理代码.

private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && Track_move==true )
            {
                Track_move = false;
                endpoint = new Point(e.X, e.Y);
                rect1 = new Rectangle(stpoint.X, stpoint.Y, endpoint.X - stpoint.X, endpoint.Y - stpoint.Y);
                Rectangle rectorg = new Rectangle(borg.X, borg.Y, image1.Width, image1.Height);
                if (rect1.Width <= 0)
                    return;
                if (rect1.Height <= 0)
                    return;
                if (rectorg.Contains(rect1))
                {
                    Rectangle rectadj = new Rectangle(rect1.X - borg.X, rect1.Y - borg.Y, rect1.Width, rect1.Height);
                    Bitmap cropimge = image1.Clone(rectadj, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    pictureBox2.Image = cropimge;
                }
                else
                {
                    pictureBox2.Image = null;
                }
                this.Invalidate();
            }
        }

程序的整个代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace imageForms
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    public partial class Form1 : Form
    {
        private System.Windows.Forms.PictureBox pictureBox2;
        private System.Windows.Forms.Label label1;
        public Form1()
        {
            InitializeComponent();
        }

private void pictureBox1_Click(object sender, EventArgs e)
        {

}

private void Form1_Load(object sender, EventArgs e)
        {
            showimg();

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71491.html