2L 的方法是可以的,如果想自己写个控件的话下面有代码,从Panel继承来,增加Image属性,运行后可以用鼠标拖动图片。。
另外,由于父类是Panel,所以可以容纳其他控件,比如Label,你可以把一个Label拖放到这个DragPictureBox里然后设置背景色为Transparent,从而使这个Label相对于图片框背景透明(由于PictureBox不是容器,所以你无法让一个Label相对于PictureBox
背景透明)
- C# code
/*
* Copyright (c) 2008 黑色珊瑚::Tsorgy.Utils, Reserved.
*
* Filename: @(#)DragPictureBox.cs
* Create by: TsOrgY
* Email: tsorgy@gmail.com
* Date: 2008/12/24 0:27:04
*
* Classname: DragPictureBox
* Description: 可拖动图片的图片框
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Tsorgy.Utils {
/// <summary>
/// 可拖动图片的图片框.
/// </summary>
[DefaultProperty("Image")]
public class DragPictureBox : Panel {
// 当前图像显示坐标.
private int _x, _y;
// 临时偏移量.
private int t_x, t_y;
/// <summary>
/// 获取或设置显示在 <see cref="Tsorgy.Utils.DragPictureBox"/> 上的图片.
/// </summary>
[Category("Appearance")]
[Description("显示在 DragPictureBox 上的图片")]
[Localizable(true)]
[DefaultValue(null)]
public Image Image {
get { return _image; }
set {
_image = value;
this.Invalidate();
}
}
private Image _image;
/// <summary>
/// 初始化 <see cref="Tsorgy.Utils.DragPictureBox"/> 类的新实例.
/// </summary>
public DragPictureBox()
: base() {
_image = null;
// 设置双缓冲.
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
/// <summary>
/// 引发 <see cref="E:System.Windows.Forms.Control.Paint"></see> 事件.
/// </summary>
/// <param >包含事件数据的 <see cref="T:System.Windows.Forms.PaintEventArgs"></see>.</param>
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
if (_image != null) {
Graphics g = e.Graphics;
g.DrawImage(_image, _x, _y, _image.Width, _image.Height);
}
}
/// <summary>
/// 引发 <see cref="E:System.Windows.Forms.Control.MouseMove"></see> 事件.
/// </summary>
/// <param >包含事件数据的 <see cref="T:System.Windows.Forms.MouseEventArgs"></see>.</param>
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
if (_image != null && e.Button == MouseButtons.Left) {
_x = e.X - t_x;
_y = e.Y - t_y;
// 防止图片拖出边缘.
if (_x > 0)
_x = 0;
else if (_x < this.Width - _image.Width)
_x = this.Width - _image.Width;
if (_y > 0)
_y = 0;
else if (_y < this.Height - _image.Height)
_y = this.Height - _image.Height;
// 重绘.
this.Invalidate(false);
}
}
/// <summary>
/// 引发 <see cref="E:System.Windows.Forms.Control.MouseDown"></see> 事件.
/// </summary>
/// <param >包含事件数据的 <see cref="T:System.Windows.Forms.MouseEventArgs"></see>.</param>
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
if (_image != null) {
t_x = e.X - _x;
t_y = e.Y - _y;
}
}
}
}
引文来源
c# picture控件中超大图片显示问题