编写带有放大镜功能的可移动透明控件。





2.00/5 (2投票s)
2006年7月11日
2分钟阅读

31340

885
本文将为您提供有关编写透明放大镜控件的基本思路。
引言
随着 .Net 中 GDI+ 的出现,图形编程变得非常容易。微软在 .net 中提供的主要功能之一是透明度,但这种透明度只能应用于窗体。为了拥有我们酷炫的透明控件,Bob Powell 在 文章 http://www.bobpowell.net/transcontrols.htm 中进行了介绍
我将继续这篇文章,编写一个也提供放大功能的控件。
编写具有放大功能的透明控件。
我们将分两个步骤开发这个放大镜控件,首先我们将编写一个透明控件,然后更改它以添加放大功能。
步骤 1
我已经编写了一个从 System.Windows.Forms.Form 继承的 TransControl 类
namespace TransControl { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { <CODE>
现在要制作这个控件,我必须做几件事,
首先,我必须通过给它一个<SPAN style="FONT-SIZE: 12pt; FONT-FAMILY: Georgia; mso-fareast-font-family: 'Times New Roman'; mso-bidi-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA">WS_EX_TRANSPARENT 样式来改变窗口的行为。这是通过重写 CreateParams 属性来完成的,以便在实例化控件时包含正确的窗口样式。
下面的列表显示了这个属性重写。
protectedoverrideCreateParams CreateParams { get { CreateParams cp=base.CreateParams; cp.ExStyle|=0x00000020; //WS_EX_TRANSPARENT returncp; } }
其次,为了确保不绘制控件背景,我们将有一个空白的 OnPaintBackground 事件,如下所示。
protected override void OnPaintBackground(PaintEventArgs pevent) { //Do not write anything here, and do not remove it. }
这样,我们的透明控件就准备好了,现在我们需要使这个控件可移动,因此我们将在类中添加这些事件,如下所示。
protected void this_MouseMove(object sender, MouseEventArgs e) { if(isMouseDown) { this.Left = this.Left + (e.X-x); this.Top = this.Top + (e.Y-y); //Refresh the parent to ensure that whatever is behind the control gets painted //before we need to do our own graphics output. this.Parent.Refresh(); } } protected void this_MouseDown(object sender, MouseEventArgs e) { x= e.X; y=e.Y; left=this.Left; top=this.Top; isMouseDown=true; this.Cursor= Cursors.SizeAll; } protected void this_MouseUp(object sender, MouseEventArgs e) { isMouseDown=false; this.Cursor= Cursors.Default; this.Refresh(); }
我们的可移动透明控件到此结束,现在我们将添加放大镜功能。
第二步
我们已经编写了透明控件,现在我们将更改它以添加放大功能
此控件应执行两件事,
1) 它应该放大选定的背景
2) 它应该支持设置 X 和 Y 偏移量,以查看特定点的放大。
对于放大,我使用了非常简单的逻辑,即,每当你在较大的画布上绘制小尺寸图像时,它看起来就像被放大了,尽管质量不是很好。
我在 TransControl 中声明了三个属性,如
public int XOffset=0; public int YOffset=0; public int MagnificationFactor=0;
TransControl 将使用这三个属性来提供放大功能。请记住,在第一步中,我们重写了 OnPaintBackground 方法并将其保留为空白,现在我们将代码添加到其中,如下所示,
protected override void OnPaintBackground(PaintEventArgs pevent) { pevent.Graphics.DrawImage(this.Parent.BackgroundImage,new Rectangle(0,0,this.Width,this.Height),this.Left + XOffset,this.Top + YOffset,this.Width-(MagnificationFactor/10),this.Height-(MagnificationFactor/10), GraphicsUnit.Pixel); }
就这样,我们准备好了可移动放大镜控件。