C# 通用控件裁剪类





5.00/5 (1投票)
为具有图像或背景图像的任何控件添加裁剪功能
在这篇文章中,我将展示如何为具有图像或背景图像的任何控件添加裁剪功能。
我热爱编程,尤其是在图形方面。
我遇到了一种情况,我需要裁剪一个简单的 PictureBox
,但它并不像预期的那么容易。
然后我想裁剪面板的背景图像,并开始为它重写代码。
我思考着如何创建一个类,使其能够通用到任何具有某种图像的控件。
就这样!这个类诞生了。
注意:可以使用鼠标右键按住并拖动裁剪矩形,将其拖动到控件内的所需区域。
使用鼠标左键按住任何拖动句柄,拖动裁剪矩形到不同的方向。
使用方法很简单
-
在窗体中创建裁剪类的实例
ControlCrop ControlrectPanel; public frmCrop() { InitializeComponent(); //Set crop control for each control that requires cropping //Set the Control in this case panel to add crop rectangle ControlrectPanel = new ControlCrop(pnlCrop); ControlrectPanel.SetControl(this.pnlCrop); //Set the Control in this case Picturebox to add crop rectangle ControlrectPicturebox = new ControlCrop(picCrop); ControlrectPicturebox.SetControl(this.picCrop); }
-
裁剪按钮的代码
private void btnCrop_Click(object sender, EventArgs e) { try { //Process Panel Rectangle rectPanel = new Rectangle (ControlrectPanel.rect.X, ControlrectPanel.rect.Y, ControlrectPanel.rect.Width, ControlrectPanel.rect.Height); //set cropped image size and creat new bitmap Bitmap _pnlimg = new Bitmap(ControlrectPanel.rect.Width, ControlrectPanel.rect.Height); //Create the original image to be cropped Bitmap OriginalPanelImage = new Bitmap(pnlCrop.BackgroundImage, pnlCrop.Width, pnlCrop.Height); //create graphic with using statement to auto close grahics using (Graphics g = Graphics.FromImage(_pnlimg)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; ////set image attributes g.DrawImage(OriginalPanelImage, 0, 0, rectPanel, GraphicsUnit.Pixel); picCroppedPanel.Image = _pnlimg; } //Process Picturebox Rectangle rectPicturebox = new Rectangle (ControlrectPicturebox.rect.X, ControlrectPicturebox.rect.Y, ControlrectPicturebox.rect.Width, ControlrectPicturebox.rect.Height); //set cropped image size and creat new bitmap Bitmap _pboximg = new Bitmap(ControlrectPicturebox.rect.Width, ControlrectPicturebox.rect.Height); //Create the original image to be cropped Bitmap OriginalPictureboxImage = new Bitmap(picCrop.Image, picCrop.Width, picCrop.Height); //Create graphic with using statement to auto close grahics using (Graphics gr = Graphics.FromImage(_pboximg)) { gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; ////set image attributes gr.DrawImage(OriginalPictureboxImage, 0, 0, rectPicturebox, GraphicsUnit.Pixel); picCropped.Image = _pboximg; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }