`

图形和 Windows 窗体

阅读更多

图形和 Windows 窗体

介绍 GDI+

公共语言运行库使用 Windows 图形设备接口 (GDI) 的高级版本,其名称为 GDI+。GDI+ 旨在提供良好的性能和易用性。它支持二维图形、版式和图像。

新的二维功能包括下列内容:

  • 对所有图形基元的 Alpha 混合支持
  • 消除锯齿
  • 渐变填充和纹理填充
  • 宽线
  • 基数样条
  • 可缩放区域
  • 浮点坐标
  • 复合线
  • 嵌入钢笔
  • 高质量的筛选和缩放
  • 大量的线型和笔尖选项

图像支持包括下列内容:

  • 对图像文件格式(如 .jpeg、.png、.gif、.bmp、.tiff、.exif 和 .icon)的本机支持
  • 用于编码和解码任意光栅图像格式的公共接口
  • 用于动态添加新图像文件格式的可扩展结构
  • 对通用点操作(如亮度、对比度、色彩平衡、模糊和溶解)的本机图像处理支持。对通用转换(如旋转、裁切等)的支持。

颜色管理

对 sRGB、ICM2 和 sRGB64 的支持

版式支持包括下列内容:

  • 本机 ClearType 支持
  • 纹理填充和渐变填充的文本
  • 在所有平台上对 Unicode 的完全支持
  • 对所有 Windows 2000 脚本的支持
  • Unicode 3.0 标准的更新
  • 文本行服务支持,可使文本更具可读性

GDI+ 可与 Windows 窗体和 Web 窗体一起使用。例如,Web 窗体控件可使用基于用户输入的 GDI+ 动态生成 .jpeg 文件,并从 Web 页引用它。

本节集中讨论 Windows 窗体。

GDI 和 GDI+ 之间的差异

本节的目的是帮助您了解使用 GDI+ 的基础知识。开始之前,有必要指出 GDI 和 GDI+ 之间的最大差异。GDI 具有有状态的编程模型,而 GDI+ 具有无状态的编程模型。使用 GDI,可在绘图表面上设置属性(如前景色和背景色),然后在它上面进行绘制。例如,若要绘制黑色文本字符串,代码有点类似于下面的示例。

function doClick(index, numTabs, id) { document.all("tab" + id, index).className = "tab"; for (var i=1; i <style type="text/css"> td.code { padding:0,10,0,10; border-style:solid; border-width:1; border-bottom:0; border-top:0; border-right:0; border-color:cccccc; background-color:ffffee } td.tab { text-align:center; font:8pt verdana; width:15%; padding:3,3,3,3; border-style:solid; border-width:1; border-right:0; border-color:black; background-color:eeeeee; cursor:hand } td.backtab { text-align:center; font: 8pt verdana; width:15%; padding:3,3,3,3; border-style:solid; border-width:1; border-right:0; border-color:black; background-color:cccccc; cursor:hand } td.space { width:70%; font: 8pt verdana; padding:0,0,0,0; border-style:solid; border-bottom:0; border-right:0; border-width:1; border-color:cccccc; border-left-color:black; background-color:white } </style>

Graphics g ;
g.ForeColor = Color.Black;
g.BackColor = Color.White;
g.Font = new Font("Times New Roman", 26);
g.DrawString("Hello, World", 0, 0);
Dim g as Graphics
g.ForeColor = Color.Black
g.BackColor = Color.White
g.Font = new Font("Times New Roman", 26)
g.DrawString("Hello, World", 0, 0)
C# VB

使用 GDI+ 时,始终将要使用的属性作为绘图命令的一部分传递。上面的代码更改为如下所示。

Graphics g ;
Color foreColor = Color.Black;
Color backColor = Color.White;
Font font = new Font("Times New Roman", 26);
g.FillRectangle(new SolidBrush(backColor), ClientRectangle);
g.DrawString("Hello World", font, new SolidBrush(foreColor), 15, 15);
Dim g As Graphics;
Dim foreColor As Color = Color.Black;
Dim backColor As Color = Color.White;
Dim vbFont As New Font("Times New Roman", 26);
g.FillRectangle(New SolidBrush(backColor), ClientRectangle);
g.DrawString("Hello World", vbFont, New SolidBrush(foreColor), 15, 15);
C# VB
GDI+ 命名空间

GDI+ 类驻留于 System.DrawingSystem.Drawing.Drawing2DSystem.Drawing.ImagingSystem.Drawing.Text 命名空间中。这些命名空间包含在程序集 System.Drawing.DLL 中。

创建图形对象

GDI+ 绘图表面由 Graphics 类表示。为了使用 GDI+,首先需要一个对图形对象的引用。通常,在控件或窗体的 Paint 事件中或者在

可以通过为 Paint 事件创建事件处理程序来处理该事件。

public class GdiPlusDemo : Form {

   public GdiPlusDemo () {
        //Hook the paint event of the form.
        this.Paint += new PaintEventHandler(form1_Paint);
    }

    private void form1_Paint(object sender, PaintEventArgs pe) {
        Graphics g = pe.Graphics;

        //Simply fill a rectangle with red.
        g.FillRectangle(new SolidBrush(Color.Red), 40, 40, 140, 140);
    }
}
Public Class GdiPlusDemo : Inherits Form

    Public Sub New()
        ' Hook the paint event of the form.
        AddHandler Me.Paint, AddressOf form1_Paint
    End Sub

    Private Sub form1_Paint(sender As Object, pe As PaintEventArgs)
        Dim g As Graphics = pe.Graphics

        ' Simply fill a rectangle with red.
        g.FillRectangle(New SolidBrush(Color.Red), 40, 40, 140, 140)
    End Sub
End Class
C# VB

更常用的是,可以创建 OnPaint 方法的子类并重写该方法。

public class GdiPlusDemo : Form {

   public GdiPlusDemo () {
   }

   protected override void OnPaint(PaintEventArgs pe) {
        Graphics g = pe.Graphics;
        g.FillRectangle(new SolidBrush(Color.Red), 40, 40, 140, 140);
    }
}
Public Class GdiPlusDemo : Inherits Form

   Public Sub New()
   End Sub

   Protected Overrides Sub OnPaint(pe As PaintEventArgs)
        Dim g As Graphics = pe.Graphics
        g.FillRectangle(New SolidBrush(Color.Red), 40, 40, 140, 140)
   End Sub
End Class
C# VB

还可以从 Image 的任何派生类创建 Graphics 对象实例。

Bitmap newBitmap = new Bitmap(600,400,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(newBitmap);
g.FillRectangle(new SolidBrush(Color.Red), 40, 40, 140, 140);
newBitmap.Save("c:\\temp\\TestImage.jpg", ImageFormat.Jpeg) ;
Dim newBitmap As Bitmap = New Bitmap(600,400,PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(newBitmap)
g.FillRectangle(New SolidBrush(Color.Red), 40, 40, 140, 140)
newBitmap.Save("c:\temp\TestImage.jpg", ImageFormat.Jpeg)
C# VB

创建 Graphics 对象后,可以使用它绘制线、填充形状、绘制文本等。与 Graphics 对象一起使用的主要对象如下所示。

Brush

用于使用图案、颜色或位图填充封闭表面。

Pen

用于绘制线和多边形,包括矩形、弧线和扇形。

Font

用于描述用来呈现文本的字体。

Color

用于描述用来呈现特定对象的颜色。在 GDI+ 中,颜色可以是 Alpha 混合效果的。

Alpha 混合
颜色可以是 Alpha 混合的,这使得易于创建基于颜色叠加的效果。例如,下面的示例绘制一个红色矩形,然后在不遮掩底层的红色矩形的情况下叠加一个黄色矩形。

Graphics g = pe.Graphics;
g.FillRectangle(new SolidBrush(Color.Red), 600, 350, 100, 100);
g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.Yellow)), 650,
                               400, 100, 100);
Dim g As Graphics = pe.Graphics
g.FillRectangle(new SolidBrush(Color.Red), 600, 350, 100, 100)
g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.Yellow)), 650, _
                               400, 100, 100)
C# VB
使用画笔
使用画笔填充形状和路径的内部。例如,若要创建红色矩形,请参见下面的示例。

Graphics g = pe.Graphics;
g.FillRectangle(new SolidBrush(Color.Red), 600, 350, 100, 100);
Dim g As Graphics = pe.Graphics
g.FillRectangle(new SolidBrush(Color.Red), 600, 350, 100, 100)
C# VB

画笔可以是纯色的、带阴影的、带纹理的或渐变的。阴影画笔只不过是使用图案进行绘画的画笔。

Graphics g = pe.Graphics;
HatchBrush hb = new HatchBrush(HatchStyle.ForwardDiagonal, Color.Green,
                               Color.FromArgb(100, Color.Yellow));
g.FillEllipse(hb, 250, 10, 100, 100);
Dim g As Graphics = pe.Graphics
HatchBrush hb = new HatchBrush(HatchStyle.ForwardDiagonal, Color.Green, _
                               Color.FromArgb(100, Color.Yellow))
g.FillEllipse(hb, 250, 10, 100, 100)
C# VB

带纹理的画笔使用位图绘画。例如,下面的代码使用纹理画笔绘制窗体的背景,然后对它应用白色"冲洗"以冲淡位图中颜色的色调。

Graphics g = pe.Graphics;
Image colorbars = new Bitmap("colorbars.jpg");
Brush backgroundBrush = new TextureBrush(colorbars);
g.FillRectangle(backgroundBrush, ClientRectangle);
g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle);
Dim g As Graphics = pe.Graphics
Dim colorbars As Image = new Bitmap("colorbars.jpg")
Dim backgroundBrush As Brush = new TextureBrush(colorbars)
g.FillRectangle(backgroundBrush, ClientRectangle)
g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle)
C# VB

LinearGradientBrush 使用两种颜色绘画。它根据在画笔上设置的属性填充给定的形状,逐渐从一种颜色过渡到另一种颜色。例如,可以用下面所示代码创建下列填充效果。



Rectangle r = new Rectangle(500, 300, 100, 100);
LinearGradientBrush lb = new LinearGradientBrush(r, Color.Red, Color.Yellow,
                                            LinearGradientMode.BackwardDiagonal);
e.Graphics.FillRectangle(lb, r);
Dim r As Rectangle = new Rectangle(500, 300, 100, 100);
Dim lb As LinearGradientBrush = new LinearGradientBrush(r, Color.Red, Color.Yellow, _
                                                       LinearGradientMode.BackwardDiagonal);
e.Graphics.FillRectangle(lb, r);
C# VB

PathGradient 画笔允许创建更复杂的效果,如下列形状。

它是用下面的代码创建的。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(backgroundBrush, ClientRectangle);
    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle);

    GraphicsPath path = new GraphicsPath(new Point[] {
        new Point(40, 140),
        new Point(275, 200),
        new Point(105, 225),
        new Point(190, 300),
        new Point(50, 350),
        new Point(20, 180),
        }, new byte[] {
            (byte)PathPointType.Start,
            (byte)PathPointType.Bezier,
            (byte)PathPointType.Bezier,
            (byte)PathPointType.Bezier,
            (byte)PathPointType.Line,
            (byte)PathPointType.Line,
            });

    PathGradientBrush pgb = new PathGradientBrush(path);
    pgb.SurroundColors = new Color[] {
        Color.Green,
        Color.Yellow,
        Color.Red,
        Color.Blue,
        Color.Orange,
        Color.White,
    };

    e.Graphics.FillPath(pgb, path);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(backgroundBrush, ClientRectangle)
    e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle)

    Dim path As New GraphicsPath(New Point() { _
        New Point(40, 140), _
        New Point(275, 200), _
        New Point(105, 225), _
        new Point(190, 300), _
        new Point(50, 350), _
        new Point(20, 180), _
        }, New Byte() { _
            CType(PathPointType.Start, Byte), _
            CType(PathPointType.Bezier, Byte), _
            CType(PathPointType.Bezier, Byte), _
            CType(PathPointType.Bezier, Byte), _
            CType(PathPointType.Line, Byte), _
            CType(PathPointType.Line, Byte), _
            })

    Dim pgb As New PathGradientBrush(path)
    pgb.SurroundColors = new Color() { _
        Color.Green, _
        Color.Yellow, _
        Color.Red, _
        Color.Blue, _
        Color.Orange, _
        Color.White, _
    }

    e.Graphics.FillPath(pgb, path)
End Sub
C# VB



<nobr><a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top"><img src="http://chs.gotdotnet.com/quickstart/winforms/images/wflink.jpg" border="1" alt=""><br></a> <table><tbody><tr> <td class="caption">VB 画笔示例</td> </tr></tbody></table> <br>[<a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top">运行示例</a>] | [<a href="http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/winforms/Samples/GDIPlus/Brushes/Brushes.src" target="_blank">查看源代码</a>] </nobr>

使用钢笔

使用钢笔绘制直线和曲线。可以设置属性,如 PenTypeDashStyleWidthColorEndCap,以控制 Pen 如何进行绘制。

下面的代码绘制一条曲线。

Graphics g;
//Create a pen 20 pixels wide that is and purple and partially transparent. 
Pen penExample = new Pen(Color.FromArgb(150, Color.Purple), 20);
//Make it a dashed pen.
Pen penExample.DashStyle = DashStyle.Dash;
//Make the ends round.
Pen penExample.StartCap = LineCap.Round;
Pen penExample.EndCap = LineCap.Round;

//Now draw a curve using the pen. 
g.DrawCurve(penExample, new Point[] {
            new Point(200, 140),
            new Point(700, 240),
            new Point(500, 340),
            new Point(140, 140),
            new Point(40, 340),
});
Dim g As Graphics
' Create a pen 20 pixels wide that is and purple and partially transparent.
Dim penExample As New Pen(Color.FromArgb(150, Color.Purple), 20)
' Make it a dashed pen.
Dim penExample.DashStyle As Pen = DashStyle.Dash
' Make the ends round.
Dim penExample.StartCap As Pen = LineCap.Round
Dim penExample.EndCap As Pen= LineCap.Round

' Now draw a curve using the pen
g.DrawCurve(penExample, New Point() { _
            New Point(200, 140), _
            New Point(700, 240), _
            New Point(500, 340), _
            New Point(140, 140), _
            New Point(40, 340), _
})
C# VB

还可以使用带纹理的画笔将纹理用作钢笔的填充效果。

Graphics g;
Brush textureBrush = new TextureBrush(new Bitmap("Boiling Point.jpg"));
Pen penExample = new Pen(textureBrush, 25);
penExample.DashStyle = DashStyle.DashDotDot;
penExample.StartCap = LineCap.Triangle;
penExample.EndCap = LineCap.Round;
g.DrawLine(penExample, 10,450,550,400);
Dim g As Graphics
Dim textureBrush As New TextureBrush(New Bitmap("Boiling Point.jpg"))
Dim penExample As New Pen(textureBrush, 25)
penExample.DashStyle = DashStyle.DashDotDot
penExample.StartCap = LineCap.Triangle
penExample.EndCap = LineCap.Round
g.DrawLine(penExample, 10,450,550,400)
C# VB



<nobr><a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top"><img src="http://chs.gotdotnet.com/quickstart/winforms/images/wflink.jpg" border="1" alt=""><br></a> <table><tbody><tr> <td class="caption">VB 笔示例</td> </tr></tbody></table> <br>[<a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top">运行示例</a>] | [<a href="http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/winforms/Samples/GDIPlus/Pens/Pens.src" target="_blank">查看源代码</a>] </nobr>

绘制文本

Graphics 对象的 DrawString 方法在绘图表面上呈现文本。将要使用的字体和颜色传递给 DrawString 方法。例如,下面的代码使用窗体的字体和黑色画笔显示文本"Hello World"。

protected override void OnPaint(PaintEventArgs e) {
    Graphics g = e.Graphics;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);
    g.DrawString("Hello World", this.Font, new SolidBrush(Color.Black), 10,10);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    Dim g As Graphics = e.Graphics
    e.Graphics.FillRectangle(New SolidBrush(Color.White), ClientRectangle)
    g.DrawString("Hello World", Me.Font, New SolidBrush(Color.Black), 10,10)
End Sub
C# VB

因为 DrawString 采用画笔,所以可以使用任何画笔呈现文本。其中包括纹理画笔。例如,下面的代码呈现具有大理石效果和背景阴影的文本。

protected override void OnPaint(PaintEventArgs e) {
    TextureBrush titleBrush = new TextureBrush(new Bitmap("marble.jpg"));
    TextureBrush backgroundBrush = new TextureBrush(new Bitmap("colorbars.jpg"));
    SolidBrush titleShadowBrush = new SolidBrush(Color.FromArgb(70, Color.Black));
    Font titleFont = new Font("Lucida Sans Unicode", 60);
    string titleText = "Graphics  Samples";

    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(backgroundBrush, ClientRectangle);
    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle);

    e.Graphics.DrawString(titleText, titleFont, titleShadowBrush, 15, 15);
    e.Graphics.DrawString(titleText, titleFont, titleBrush, 10, 10);

}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    Dim titleBrush As New TextureBrush(New Bitmap("marble.jpg"))
    Dim backgroundBrush As New TextureBrush(New Bitmap("colorbars.jpg"))
    Dim titleShadowBrush As New SolidBrush(Color.FromArgb(70, Color.Black))
    Dim titleFont As New Font("Lucida Sans Unicode", 60)
    Dim titleText As String = "Graphics  Samples"

    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(backgroundBrush, ClientRectangle)
    e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(180, Color.White)), ClientRectangle)

    e.Graphics.DrawString(titleText, titleFont, titleShadowBrush, 15, 15)
    e.Graphics.DrawString(titleText, titleFont, titleBrush, 10, 10)

End Sub
C# VB

如果提供带有 RectangleDrawString,则文本将换行以适合该矩形。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);

    Font textFont = new Font("Lucida Sans Unicode", 12);
    RectangleF rectangle = new RectangleF(100, 100, 250, 350);
    e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle);
    string flowedText="Simplicity and power: Windows Forms is a programming model for\n"
        + "developing Windows applications that combines the simplicity of the Visual\n"
        + "Basic 6.0 programming model with the power and flexibility of the common\n"
        + "language runtime.\n"
        + "Lower total cost of ownership: Windows Forms takes advantage of the versioning and\n"
        + "deployment features of the common language runtime to offer reduced deployment\n"
        + "costs and higher application robustness over time. This significantly lowers the\n"
        + "maintenance costs (TCO) for applications\n"
        + "written in Windows Forms.\n"
        + "Architecture for controls: Windows Forms offers an architecture for\n"
        + "controls and control containers that is based on concrete implementation of the\n"
        + "control and container classes. This significantly reduces\n"
        + "control-container interoperability issues.\n";
    e.Graphics.DrawString(flowedText, textFont, new SolidBrush(Color.Blue), rectangle);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(New SolidBrush(Color.White), ClientRectangle)

    Dim textFont As New Font("Lucida Sans Unicode", 12)
    Dim rectangle As New RectangleF(100, 100, 250, 350)
    e.Graphics.FillRectangle(New SolidBrush(Color.Gainsboro), rectangle)
    Dim flowedText As String ="Simplicity and power: Windows Forms is a programming model for" & ControlChars.CrLf _
        & "developing Windows applications that combines the simplicity of the Visual" & ControlChars.CrLf _
        & "Basic 6.0 programming model with the power and flexibility of the common" & ControlChars.CrLf _
        & "language runtime." & ControlChars.CrLf _
        & "Lower total cost of ownership: Windows Forms takes advantage of the versioning and" & ControlChars.CrLf _
        & "deployment features of the common language runtime to offer reduced deployment" & ControlChars.CrLf _
        & "costs and higher application robustness over time. This significantly lowers the" & ControlChars.CrLf _
        & "maintenance costs (TCO) for applications" & ControlChars.CrLf _
        & "written in Windows Forms." & ControlChars.CrLf _
        & "Architecture for controls: Windows Forms offers an architecture for" & ControlChars.CrLf _
        & "controls and control containers that is based on concrete implementation of the" & ControlChars.CrLf _
        & "control and container classes. This significantly reduces" & ControlChars.CrLf _
        & "control-container interoperability issues." & ControlChars.CrLf
    e.Graphics.DrawString(flowedText, textFont, New SolidBrush(Color.Blue), rectangle)
End Sub
C# VB

可以使用 StringFormat 对象控制如何绘制文本。例如,下面的代码使您得以绘制在特定区域内居中的文本。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);

    Font textFont = new Font("Lucida Sans Unicode", 8);
    RectangleF rectangle = new RectangleF(100, 100, 250, 350);
    e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle);
    StringFormat format = new StringFormat();
    format.Alignment=StringAlignment.Center;
    string flowedText="Simplicity and power: Windows Forms is a programming model for\n"
        + "developing Windows applications that combines the simplicity of the Visual\n"
        + "Basic 6.0 programming model with the power and flexibility of the common\n"
        + "language runtime.\n"
        + "Lower total cost of ownership: Windows Forms takes advantage of the versioning and\n"
        + "deployment features of the common language runtime to offer reduced deployment\n"
        + "costs and higher application robustness over time. This significantly lowers the\n"
        + "maintenance costs (TCO) for applications\n"
        + "written in Windows Forms.\n"
        + "Architecture for controls: Windows Forms offers an architecture for\n"
        + "controls and control containers that is based on concrete implementation of the\n"
        + "control and container classes. This significantly reduces\n"
        + "control-container interoperability issues.\n";
    e.Graphics.DrawString(flowedText, textFont, new SolidBrush(Color.Blue), rectangle,format);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(New SolidBrush(Color.White), ClientRectangle)

    Dim textFont As New Font("Lucida Sans Unicode", 8)
    Dim rectangle As New RectangleF(100, 100, 250, 350)
    e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle)
    Dim format As New StringFormat()
    format.Alignment = StringAlignment.Center
    Dim flowedText As String ="Simplicity and power: Windows Forms is a programming model for" & ControlChars.CrLf _
        & "developing Windows applications that combines the simplicity of the Visual" & ControlChars.CrLf _
        & "Basic 6.0 programming model with the power and flexibility of the common" & ControlChars.CrLf _
        & "language runtime." & ControlChars.CrLf _
        & "Lower total cost of ownership: Windows Forms takes advantage of the versioning and" & ControlChars.CrLf _
        & "deployment features of the common language runtime to offer reduced deployment" & ControlChars.CrLf _
        & "costs and higher application robustness over time. This significantly lowers the" & ControlChars.CrLf _
        & "maintenance costs (TCO) for applications" & ControlChars.CrLf _
        & "written in Windows Forms." & ControlChars.CrLf _
        & "Architecture for controls: Windows Forms offers an architecture for" & ControlChars.CrLf _
        & "controls and control containers that is based on concrete implementation of the" & ControlChars.CrLf _
        & "control and container classes. This significantly reduces" & ControlChars.CrLf _
        & "control-container interoperability issues." & ControlChars.CrLf
    e.Graphics.DrawString(flowedText, textFont, New SolidBrush(Color.Blue), rectangle,format)
End Sub
C# VB

如果要在绘制字符串时确定该字符串的长度,可使用 MeasureString。例如,若要将某个字符串在窗体上居中显示,请使用下面的代码。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);

    string textToDraw="Hello Symetrical World";

    Font textFont = new Font("Lucida Sans Unicode", 8);
    float windowCenter=this.DisplayRectangle.Width/2;
    SizeF stringSize=e.Graphics.MeasureString(textToDraw, textFont);
    float startPos=windowCenter-(stringSize.Width/2);

    e.Graphics.DrawString(textToDraw, textFont, new SolidBrush(Color.Blue), startPos, 40);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle)

    Dim textToDraw As String ="Hello Symetrical World"

    Dim textFont As New Font("Lucida Sans Unicode", 8)
    Dim windowCenter As Double = this.DisplayRectangle.Width/2
    Dim stringSize As SizeF = e.Graphics.MeasureString(textToDraw, textFont)
    Dim startPos As Double = windowCenter-(stringSize.Width/2)

    e.Graphics.DrawString(textToDraw, textFont, new SolidBrush(Color.Blue), startPos, 40)
End Sub
C# VB

MeasureString 还可用于确定呈现多少行和多少个字符。例如,我们可以确定在上一个讨论过的文本示例中呈现多少行和多少个字符。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);

    Font textFont = new Font("Lucida Sans Unicode", 12);
    RectangleF rectangle = new RectangleF(100, 100, 250, 350);
    int lines;
    int characters;
    string flowedText="Simplicity and power: Windows Forms is a programming model for\n"
        + "developing Windows applications that combines the simplicity of the Visual\n"
        + "Basic 6.0 programming model with the power and flexibility of the common\n"
        + "language runtime.\n"
        + "Lower total cost of ownership: Windows Forms takes advantage of the versioning and\n"
        + "deployment features of the common language runtime to offer reduced deployment\n"
        + "costs and higher application robustness over time. This significantly lowers the\n"
        + "maintenance costs (TCO) for applications\n"
        + "written in Windows Forms.\n"
        + "Architecture for controls: Windows Forms offers an architecture for\n"
        + "controls and control containers that is based on concrete implementation of the\n"
        + "control and container classes. This significantly reduces\n"
        + "control-container interoperability issues.\n";
    string whatRenderedText;

    e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle);

    e.Graphics.MeasureString(flowedText, textFont, rectangle.Size,
                    new StringFormat(), out characters, out lines);
    whatRenderedText="We printed " + characters + " characters and " + lines + " lines";

    e.Graphics.DrawString(flowedText, textFont, new SolidBrush(Color.Blue), rectangle);

    e.Graphics.DrawString(whatRenderedText, this.Font, new SolidBrush(Color.Black), 10,10);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle)

    Dim textFont As New Font("Lucida Sans Unicode", 12)
    Dim rectangle As New RectangleF(100, 100, 250, 350)
    Dim lines As Integer
    Dim characters As Integer
    Dim flowedText As String ="Simplicity and power: Windows Forms is a programming model for" & ControlChars.CrLf _
        & "developing Windows applications that combines the simplicity of the Visual" & ControlChars.CrLf _
        & "Basic 6.0 programming model with the power and flexibility of the common" & ControlChars.CrLf _
        & "language runtime." & ControlChars.CrLf _
        & "Lower total cost of ownership: Windows Forms takes advantage of the versioning and" & ControlChars.CrLf _
        & "deployment features of the common language runtime to offer reduced deployment" & ControlChars.CrLf _
        & "costs and higher application robustness over time. This significantly lowers the" & ControlChars.CrLf _
        & "maintenance costs (TCO) for applications" & ControlChars.CrLf _
        & "written in Windows Forms." & ControlChars.CrLf _
        & "Architecture for controls: Windows Forms offers an architecture for" & ControlChars.CrLf _
        & "controls and control containers that is based on concrete implementation of the" & ControlChars.CrLf _
        & "control and container classes. This significantly reduces" & ControlChars.CrLf _
        & "control-container interoperability issues." & ControlChars.CrLf
    Dim whatRenderedText As String

    e.Graphics.FillRectangle(New SolidBrush(Color.Gainsboro), rectangle)

    e.Graphics.MeasureString(flowedText, textFont, rectangle.Size, _
                    new StringFormat(), characters, lines)
    whatRenderedText = "We printed " & characters & " characters and " & lines & " lines"

    e.Graphics.DrawString(flowedText, textFont, New SolidBrush(Color.Blue), rectangle)

    e.Graphics.DrawString(whatRenderedText, Me.Font, New SolidBrush(Color.Black), 10,10)
End Sub
C# VB

GDI+ 完全支持 Unicode。这意味着可以用任何语言呈现文本。例如,下面的代码用日语绘制字符串(必须安装有日语语言包)。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased;
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);

    try {
        Font japaneseFont = new Font("MS Mincho", 32);
        string japaneseText = new string(new char[] {(char)31169, (char)12398, (char)21517,
                    (char)21069, (char)12399, (char)12463, (char)12522, (char)12473,
                    (char)12391, (char)12377, (char)12290});

        e.Graphics.DrawString(japaneseText, japaneseFont, new SolidBrush(Color.Blue), 20, 40);
    } catch (Exception ex) {
         MessageBox.Show("You need to install the Japanese language pack to run this sample");
         Application.Exit();
    }
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliased
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle)

    Try
        Dim japaneseFont As New Font("MS Mincho", 32)
        Dim japaneseText As New String(new char() {CType(31169, Char), CType(12398, Char), _
                    CType(21517, Char), CType(21069, Char), CType(12399, Char), _
                    CType(12463, Char), CType(12522, Char), CType(12473, Char), _
                    CType(12391, Char), CType(12377, Char), CType(12290, Char)})
        e.Graphics.DrawString(japaneseText, japaneseFont, new SolidBrush(Color.Blue), 20, 40)
    Catch ex As Exception
         MessageBox.Show("You need to install the Japanese language pack to run this sample")
         Application.Exit()
    End Try
End Sub
C# VB


<nobr><a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top"><img src="http://chs.gotdotnet.com/quickstart/winforms/images/wflink.jpg" border="1" alt=""><br></a> <table><tbody><tr> <td class="caption">VB 文本示例</td> </tr></tbody></table> <br>[<a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top">运行示例</a>] | [<a href="http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/winforms/Samples/GDIPlus/Text/Text.src" target="_blank">查看源代码</a>] </nobr>

使用图像

GDI+ 完全支持各种图像格式,包括 .jpeg、.png、.gif、.bmp、.tiff、.exif 和 .icon 文件。

呈现图像非常简单。例如,下面的代码呈现一个 .jpeg 图像。

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.FillRectangle(new SolidBrush(Color.White), ClientRectangle);
    e.Graphics.DrawImage(new Bitmap("sample.jpg"), 29, 20, 283, 212);
}
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.FillRectangle(New SolidBrush(Color.White), ClientRectangle)
    e.Graphics.DrawImage(New Bitmap("sample.jpg"), 29, 20, 283, 212)
End Sub
C# VB

使用位图作为呈现图面也非常简单。下面的代码将一些文本和线呈现到位图上,然后将该位图作为 .png 文件保存到磁盘中。

Bitmap newBitmap = new Bitmap(800,600,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(newBitmap);
g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0,0,800,600));

Font textFont = new Font("Lucida Sans Unicode", 12);
RectangleF rectangle = new RectangleF(100, 100, 250, 350);
int lines;
int characters;
string flowedText="Simplicity and power: Windows Forms is a programming model for\n"
    + "developing Windows applications that combines the simplicity of the Visual\n"
    + "Basic 6.0 programming model with the power and flexibility of the common\n"
    + "language runtime.\n"
    + "Lower total cost of ownership: Windows Forms takes advantage of the versioning and\n"
    + "deployment features of the common language runtime to offer reduced deployment\n"
    + "costs and higher application robustness over time. This significantly lowers the\n"
    + "maintenance costs (TCO) for applications\n"
    + "written in Windows Forms.\n"
    + "Architecture for controls: Windows Forms offers an architecture for\n"
    + "controls and control containers that is based on concrete implementation of the\n"
    + "control and container classes. This significantly reduces\n"
    + "control-container interoperability issues.\n";

g.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle);
g.DrawString(flowedText, textFont, new SolidBrush(Color.Blue), rectangle);
Pen penExample = new Pen(Color.FromArgb(150, Color.Purple), 20);
penExample.DashStyle = DashStyle.Dash;
penExample.StartCap = LineCap.Round;
penExample.EndCap = LineCap.Round;
g.DrawCurve(penExample, new Point[] {
            new Point(200, 140),
            new Point(700, 240),
            new Point(500, 340),
            new Point(140, 140),
            new Point(40, 340),
});

newBitmap.Save("TestImage.png", ImageFormat.Png) ;
Dim newBitmap As New Bitmap(800,600,PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(newBitmap)
g.FillRectangle(New SolidBrush(Color.White), new Rectangle(0,0,800,600))

Dim textFont As New Font("Lucida Sans Unicode", 12)
Dim rectangle As New RectangleF(100, 100, 250, 350)
Dim Lines As Integer
Dim Characters As Integer
Dim flowedText As String ="Simplicity and power: Windows Forms is a programming model for" & ControlChars.CrLf _
    & "developing Windows applications that combines the simplicity of the Visual" & ControlChars.CrLf _
    & "Basic 6.0 programming model with the power and flexibility of the common" & ControlChars.CrLf _
    & "language runtime." & ControlChars.CrLf _
    & "Lower total cost of ownership: Windows Forms takes advantage of the versioning and" & ControlChars.CrLf _
    & "deployment features of the common language runtime to offer reduced deployment" & ControlChars.CrLf _
    & "costs and higher application robustness over time. This significantly lowers the" & ControlChars.CrLf _
    & "maintenance costs (TCO) for applications" & ControlChars.CrLf _
    & "written in Windows Forms." & ControlChars.CrLf _
    & "Architecture for controls: Windows Forms offers an architecture for" & ControlChars.CrLf _
    & "controls and control containers that is based on concrete implementation of the" & ControlChars.CrLf _
    & "control and container classes. This significantly reduces" & ControlChars.CrLf _
    & "control-container interoperability issues." & ControlChars.CrLf

g.FillRectangle(new SolidBrush(Color.Gainsboro), rectangle)
g.DrawString(flowedText, textFont, new SolidBrush(Color.Blue), rectangle)
Dim penExample As New Pen(Color.FromArgb(150, Color.Purple), 20)
penExample.DashStyle = DashStyle.Dash
penExample.StartCap = LineCap.Round
penExample.EndCap = LineCap.Round
g.DrawCurve(penExample, new Point() { _
            new Point(200, 140), _
            new Point(700, 240), _
            new Point(500, 340), _
            new Point(140, 140), _
            new Point(40, 340), _
})

newBitmap.Save("TestImage.png", ImageFormat.Png)
C# VB



<nobr><a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top"><img src="http://chs.gotdotnet.com/quickstart/winforms/images/wflink.jpg" border="1" alt=""><br></a> <table><tbody><tr> <td class="caption">VB 图像示例</td> </tr></tbody></table> <br>[<a href="http://chs.gotdotnet.com/quickstart/setup.aspx?ReturnUrl=http://chs.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx" target="_top">运行示例</a>] | [<a href="http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/winforms/Samples/GDIPlus/Images/Images.src" target="_blank">查看源代码</a>] </nobr>

其他信息
标准钢笔和画笔

PenBrush 类包括一组用于所有已知颜色的标准纯色钢笔和画笔。

消除锯齿
Graphics.SmoothingMode 设置为 SmoothingMode.AntiAlias 将导致更锐化的文本和图形。
图形对象的范围
Paint 事件的参数 (PaintEventArgs) 中包含的图形对象根据 Paint 事件处理程序的返回结果进行处置。因此,不应保持对范围超出 Paint 事件之外的此 Graphics 对象的引用。尝试在 Paint 事件之外使用此 Graphics 对象将出现不可预知的结果。
处理调整大小

默认情况下,当调整控件或窗体大小时不引发 Paint 事件。如果希望在调整窗体大小时引发 Paint 事件,则需要相应地设置控件样式。

public MyForm() {
    SetStyle(ControlStyles.ResizeRedraw,true);
}
Public Sub MyForm()
    SetStyle(ControlStyles.ResizeRedraw,True)
End Sub
C# VB

转自 http://www.gotdotnet.com/

PrintDocumentPrintPage 事件中获取对图形对象的引用。
分享到:
评论

相关推荐

    第9章 Windows窗体界面与图形设计.doc

    第9章 Windows窗体界面与图形设计

    Mobile移动开发宝典_第02章 构建Windows窗体GUI

    本章和下一章将介绍如何为移动应用程序构建Microsoft Windows窗体GUI(Graphical User Interface,图形用户接口)。在本章中,将学习窗体的管理和导航,处理用户输入和不同的屏幕方向与分辨率,Pocket PC 与Smartphone...

    生成半圆形窗体

    生成半圆形窗体

    基于VB.NET的Windows应用程序设计

    课程简介 本课程介绍使用VB.NET...第6章 Windows窗体应用程序中的报表和打印 第7章 异步编程 第8章 增强应用程序的可用性 第9章 部署Windows窗体应用程序 第10章 Windows窗体应用程序的安全性 参考资料 互联网资源 ...

    第二章 01窗体基类介绍及简单应用

    本课程以C++编程为导向来详细介绍Qt编程,课程包括十四个部分,分别介绍Qt的编程环境、窗体应用、控件应用、组件应用、文件操作、图形图像操作、多媒体应用、对系统操作、对注册表操作、数据库应用,网络应用开发、...

    c#窗体验证码

    当画完画之后,(这里相当于生成了一张)我们需要有一个相框将我们画的画装裱起来,这里的相框相当于windows窗体程序中的picturebox,而紧接着我们需要将相框放在墙上悬挂起来。这里的墙体相当于windows中的form窗体...

    如何用画笔,画图板画几何图形

    对Windows窗体对象进行绘制工作,实现与显示设备进行交互。此文件还运用到了Color类用于管理颜色,提供了许多默认的颜色设置,还有画刷,这里画刷用于图形颜色的填充。还有画笔用来画几何图形。还能教你如何运用图形...

    windows应用高级编程-C#编程篇

    1.1.1 Windows窗体的概念 1.1.2 System.Windows.Forms命名空间 1.2 Visual Studio.NET IDE简介 1.2.1 解决方案和项目 1.2.2 Toolbox和Properties窗口 1.2.3 动态帮助窗口 1.2.4 类现图 1.2.5 对象浏览器 1.2.6 代码...

    C#定义基类并重写基类方法计算图形面积和周长的windows界面程序

    1.定义基类Shape,这有求面积的虚方法Mianji();求周长的虚方法Zhouchang()。...点击按钮,根据用户所选择的形状接收用户输入的参数,申明基类引用,通过基类引用接收派生类对象将求出的面积和周长值显示到窗体。

    c++builder 用png 图片做的窗体背景半透明 加入动画效果

    c++builder 用png图片做的窗体背景半透明,加入动画效果,放了背景透明的两条鱼在那里游动,不需要用额外的技术,只是直接加入png图片。

    C#二维三维图形绘制工程实例宝典 随书光盘

    9.4.2 windows窗体上的嵌入式excel图表 631 第五部分 实现文件的相关知识 第10章 文件的读/写 634 10.1 c#文件读/写常用类 634 10.1.1 system.io.file类和system.io.fileinfo类 634 10.1.2 system.io....

    C#GDI+图形程序设计源码

    c#图形书中最经典的一本书当中包括饼图,条形...15.2 绘制具有形状的窗体和Windows控件 15.3 为绘制的图像添加版权信息 15.4 从流或数据库读取及写入图像 15.5 创建自绘制的列表控件 总结 附录A .NET中的异常处理

    基于C语言设计的无边框背景透明窗体.zip

    简单来说就是找到桌面 Program Manager,给桌面发送 0x52c 消息,让它接触父子关系,然和将自己写好的窗口和它建立父子关系 `SetParent` 详细介绍参考:https://blog.csdn.net/newlw/article/details/124913995

    计算器的简单实现C#窗体

    是一个很简单的计算器程序.// 用C#写的.. WINDOWS窗体..

    python Tkinker窗体 登录、注册窗体实例

    它将展示如何使用 Python 中的 tkinter 库来创建图形用户界面 (GUI),并使用输入框、按钮、标签等控件来实现登录/注册功能。 适合人群:完全没有 Python 基础的程序员,希望了解如何使用 Python 创建 GUI 的开发人员...

    KOL(编写非常小的32位Windows图形用户界面 v2.80)

    KOL是一套对象库,免费而且开放源代码,它能够使Delphi编出尺寸非常小的32位Windows图形用户界面的应用程序。 目前支持的Delphi版本:Delphi7,Delphi6,Delphi5,Delphi4,Delphi3和Delphi2。 使用KOL在D2-D5中...

    NodeEditorWinforms:Windows窗体的基于节点的用户控件编辑器

    它包含Windows窗体用户控件,在将其引用到您的项目后,可以通过Visual Studio中的UI设计器添加。变更日志2021.01.24-添加了通过NodeVisual的CustomEditor属性访问节点自定义编辑器的功能2021.01.24-解决程序集的...

    用c#编写的二叉树的图形化显示

    这是一个用c#编写的windows应用程序,写的是二叉树在windows窗体上的生成显示

    C#二维三维图形绘制工程实例宝典

    9.4.2 Windows窗体上的嵌入式Excel图表 第五部分 实现文件的相关知识 第10章 文件的读/写 10.1 C#文件读/写常用类 10.1.1 System.IO.File类和System.IO.FileI nfo类 10.1.2 System.IO.Directory类和System.Dir ...

    Windows版验证码生成程序

    本程序是采用Windows GDI+技术模拟Web上的验证码生成而设计的一款Windows版验证码随机生成程序,利用GDI+图形图像处理技术,可随机生成强验证码(即汉字...主要涉及到窗体和控件的使用以及GDI+图形图像程序设计 。

Global site tag (gtag.js) - Google Analytics