图形图像编程

1.1   GDI+概述

1.1.1          Graphics

Graphics类包含在System.Drawing名称空间下。要进行图形处理,必须首先创建Graphics对象,然后才能利用它进行各种图画操作。创建Graphics对象的形式有:

1. 在窗体或控件的Paint事件中直接引用Graphics对象。

Private void Form_Paint(object sender,System.Windows.Forms.PaintEventArgs e)

{

             Grahpics g=e.Graphics;

}

2. 从当前窗体获取对Graphics对象的引用。

Graphics g=this.CreateGraphics();

3. 从继承自图像的任何对象创建Graphics对象。

Bitmap bitmap=new Bitmap(@”C:\test\a1.bmp”);

Graphics g=Graphics.FromImage(bitmap);

1.1.2          颜色

1. 使用FromArgh制定任意颜色。

这个方法有两种常用的形式,第一种形式是指定3种颜色,方法原型为:

Public static Color FromArgb(int red,int green,int blue)

第二种形式使用4格参数,格式为:

public static Color FromArgb(int alpha,int red,int green,int blue)

2. 使用系统预定义颜色。

实际上,在Color结构中已经定义了141中颜色,可以直接使用。

Color myColor;

myColor=Color.Red;

1.1.3          笔和画刷

1. 笔(Pen

Pen myPen = new Pen(Color.Black);//创建一支黑色笔,宽度默认为1个像素

Pen myPen = new Pen(Color.Black, 5);//创建一支宽度为5个像素的黑色笔

SolidBrush myBrush = new SolidBrush(Color.Red);//实心画刷,默认宽度为1个像素

            Pen myPen = new Pen(myBrush);//从现有画刷创建红色笔

Pen myPen = new Pen(myBrush, 5);//从现有画刷创建宽度为5个像素的红色笔

 

 private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen pen = new Pen(Color.Blue, 10.5f);//构造一支宽度为10.5个像素的红色笔

            g.DrawString("蓝色,宽度为10.5", this.Font, new SolidBrush(Color.Black), 5,5);

            g.DrawLine(pen, new Point(110, 10), new Point(380, 10));

            pen.Width = 2;

            pen.Color = Color.Red;

            g.DrawString("红色,宽度为2", this.Font, new SolidBrush(Color.Black), 5, 25);

            g.DrawLine(pen, new Point(110, 30), new Point(380, 30));

            pen.StartCap = LineCap.Flat;

            pen.EndCap = LineCap.ArrowAnchor;

            pen.Width = 9;

            g.DrawString("红色箭头线", this.Font, new SolidBrush(Color.Black), 5, 45);

            g.DrawLine(pen, new Point(110, 50), new Point(380, 50));

            pen.DashStyle = DashStyle.Custom;

            pen.DashPattern = new float[] { 4, 4 };

            pen.Width = 2;

            pen.EndCap = LineCap.NoAnchor;

            g.DrawString("自定义虚线", this.Font, new SolidBrush(Color.Black), 5, 65);

            g.DrawLine(pen, new Point(110, 70), new Point(380, 70));

            pen.DashStyle = DashStyle.Dot;

            g.DrawString("点划线", this.Font, new SolidBrush(Color.Black), 5, 85);

            g.DrawLine(pen, new Point(110, 90), new Point(380, 90));

}

 

 

2. 画刷(Brush

Brush

说明

SolidBrush

画刷的简单形式,用纯色进行填充。

HatchBrush

类似于SilidBrush,但是可以利用该类从大量与设计的图案中选择绘制时要使用的图案,而不是纯色。

TexttureBrush

使用纹理(如图像)进行绘制。

LinearGradientBrush

使用混合渐变的两种颜色进行填充。

PathGradientBrush

基于编程者定义的唯一路径,使用复杂的混合渐变进行填充。

1. 单色画刷演示:

private void Form1_Paint(object sender, PaintEventArgs e)

              {

                   Graphics g = e.Graphics;

                   SolidBrush myBrush = new SolidBrush(Color.Red);

                   g.FillEllipse(myBrush, this.ClientRectangle);

}

 

2. 填充简单图案演示

private void Form1_Paint(object sender, PaintEventArgs e)

              {

                   Graphics g = e.Graphics;

                    HatchBrush aHatchBrush = new HatchBrush(HatchStyle.Percent90, Color.Yellow, Color.Green);

                   g.FillEllipse(aHatchBrush, this.ClientRectangle);

}

 

3. 创建TextureBrush掩饰

private void Form1_Paint(object sender, PaintEventArgs e)

{

                   Graphics g = e.Graphics;

                   //根据文件名创建原始大小的bitmap对象

                    Bitmap bitmap = new Bitmap(@"\mm.jpg");

                    //将其缩放到当前窗体大小

                   bitmap = new Bitmap(bitmap, this.ClientRectangle.Size);

                   TextureBrush myBrush = new TextureBrush(bitmap);

                   g.FillEllipse(myBrush, this.ClientRectangle);

}

 

4. 使用LinearGradientBrush演示

private void Form1_Paint(object sender, PaintEventArgs e)

              {

                   Graphics g = e.Graphics;

                   LinearGradientBrush myBrush = new LinearGradientBrush(this.ClientRectangle, Color.White, Color.Blue, LinearGradientMode.Vertical);

                   g.FillRectangle(myBrush, this.ClientRectangle);

}

 

5. 使用PathGradientBrush演示路径和路径画刷的使用

private void Form1_Paint(object sender, PaintEventArgs e)

              {

                    Graphics g = e.Graphics;

                    Point centerPoint = new Point(150, 100);

                    int R = 60;

                    GraphicsPath path = new GraphicsPath();

                   path.AddEllipse(centerPoint.X - R, centerPoint.Y - R, 2 * R, 2 * R);

                     PathGradientBrush brush = new PathGradientBrush(path);

                   //指定路径中心点

                    brush.CenterPoint = centerPoint;

                    //指定路径中心的颜色

                    brush.CenterColor = Color.Red;

                    //Color类型的数组指定与路径上每个顶点的颜色

                    brush.SurroundColors = new Color[] { Color.Plum };

                    g.FillEllipse(brush, centerPoint.X - R, centerPoint.Y - R, 2 * R, 2 * R);

                   centerPoint = new Point(350, 100);

                    R = 20;

                    path = new GraphicsPath();

                    path.AddEllipse(centerPoint.X - R, centerPoint.Y - R, 2 * R, 2 * R);

                    path.AddEllipse(centerPoint.X - 2*R, centerPoint.Y - 2*R, 4 * R, 4 * R);

                    path.AddEllipse(centerPoint.X - 3*R, centerPoint.Y - 3*R, 6 * R, 6 * R);

                    brush = new PathGradientBrush(path);

                   brush.CenterPoint = centerPoint;

                    brush.CenterColor = Color.Red;

                   brush.SurroundColors = new Color[] { Color.Black, Color.Blue, Color.Green };

                   g.FillPath(brush, path);

}

 

1.1.4          平移、旋转和缩放

1. public void TranslateTransform(float dx,float dy)

dx表示平移的x分量,dy表示平移y分量

2. public void RotateTransform(float angle)

angle表示旋转的角度

3. public void ScaleTransform(ffoat sx,float sy)

sx表示x方向的缩放比例,sy表示y方向的缩放比例

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            //椭圆透明度为80%

            g.FillEllipse(new SolidBrush(Color.FromArgb(80, Color.Red)), 120, 30, 200, 100);

            //顺时针旋转30

            g.RotateTransform(30.0f);

            g.FillEllipse(new SolidBrush(Color.FromArgb(80, Color.Blue)), 120, 30, 200, 100);

            //水平方向向右平移200个像素,垂直方向向上平移100个像素

            g.TranslateTransform(200.0f, -100.0f);

            g.FillEllipse(new SolidBrush(Color.FromArgb(50, Color.Green)), 120, 30, 200, 100);

            //缩小到一半

            g.ScaleTransform(0.5f, 0.5f);

            g.FillEllipse(new SolidBrush(Color.FromArgb(100, Color.Red)), 120, 30, 200, 100);

}

 

1.2   绘制图形

1.2.1          直线

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen blackPen = new Pen(Color.Black, 3);

            Point point1 = new Point(100, 100);

            Point point2 = new Point(200, 100);

            g.DrawLine(blackPen, point1, point2);

}

 

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen pen = new Pen(Color.Black, 3);

            Point[] points =

                {

                    new Point(10,10),

                    new Point(10,100),

                    new Point(200,50),

                    new Point(250,120)

                };

            g.DrawLines(pen, points);

 }

 

1.2.2          矩形

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen pen = new Pen(Color.Black, 3);

            Rectangle rect = new Rectangle(30, 30, 200, 100);

            g.DrawRectangle(pen, rect);

}

 

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen pen = new Pen(Color.Red, 3);

            Rectangle[] rects =

                {

                    new Rectangle(0,0,100,200),

                    new Rectangle(100,200,250,50),

                    new Rectangle(300,0,50,100)

                };

            g.DrawRectangles(pen, rects);

}

 

1.2.3          多边形

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            Pen pen = new Pen(Color.Red);

            Point[] points =

                {

                    new Point(50,50),

                    new Point(100,100),

                    new Point(75,150),

                    new Point(25,150),

                    new Point(0,100)

                };

            g.DrawPolygon(pen, points);

            points = new Point[]

            {

                new Point(250,50),

                new Point(300,100),

                new Point(275,150),

                new Point(225,150),

                new Point(200,100)

            };

            g.FillPolygon(new SolidBrush(Color.Yellow), points);

 }

 

1.2.4          曲线

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Pen redPen = new Pen(Color.Red, 3);

            Pen greenPen = new Pen(Color.Green, 3);

            Point[] curvePoints =

                {

                    new Point(50,250),

                    new Point(100,25),

                    new Point(200,250),

                    new Point(250,50),

                    new Point(300,75),

                    new Point(350,200),

                    new Point(400,150)

                };

            e.Graphics.DrawLines(redPen, curvePoints);

            e.Graphics.DrawCurve(greenPen, curvePoints);

 }

 

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Pen redPen = new Pen(Color.Red, 3);

            Pen greenPen = new Pen(Color.Green, 3);

            Point[] curvePoints =

                {

                    new Point(50,250),

                    new Point(100,25),

                    new Point(200,250),

                    new Point(250,50),

                    new Point(300,75),

                    new Point(350,200),

                    new Point(400,150)

                };

            e.Graphics.DrawLines(redPen, curvePoints);

            e.Graphics.DrawClosedCurve(greenPen, curvePoints);

}

 

private void Form1_Paint(object sender, PaintEventArgs e)

     {

            Graphics g = e.Graphics;

            Pen redPen = new Pen(Color.Red, 3);

            Pen greenPen=new Pen(Color.Green,3);

            Point[] bezierPoints =

                {

                    new Point(50,250),

                    new Point(100,25),

                    new Point(200,250),

                    new Point(250,50),

                    new Point(300,75),

                    new Point(350,200),

                    new Point(400,150)

                };

            g.DrawLines(greenPen, bezierPoints);

            g.DrawBeziers(redPen, bezierPoints);

}

 

1.2.5          椭圆

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Pen redPen = new Pen(Color.Red, 3);

            e.Graphics.DrawEllipse(redPen, 20, 20, 200, 200);

}

 

1.3   图像的显示与保存

1.3.1          显示图像

1. 创建Bitmap对象

public Bitmap(string filename)

2. DrawInage方法

public void DrawImage(Image image,int x,int y,int width,int height)

private void button1_Click(object sender, EventArgs e)

         {

            OpenFileDialog file = new OpenFileDialog();

            file.Filter = "*.jpg;*.bmp|*.jpg;*.bmp";

            if (file.ShowDialog() == DialogResult.OK)

            {

                Bitmap bitmap = new Bitmap(file.FileName);

                Graphics g = this.CreateGraphics();

                g.DrawImage(bitmap, 3, 10, 200, 200);

                g.DrawImage(bitmap, 250, 10, 50, 50);

                g.DrawImage(bitmap, 350, 10, bitmap.Width / 2, bitmap.Height / 2);

                //使用此类对象时,不要忘记及时释放占用的资源,否则将会严重影响系统的行能

                bitmap.Dispose();

                g.Dispose();

           }

        }

 

1.3.2          保存图像

private void button1_Click(object sender, EventArgs e)

        {

            Graphics g = this.CreateGraphics();

            DrawMyImage(g);

            g.Dispose();

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            //构造一个指定区域的空图像

            Bitmap image = new Bitmap(this.Width, this.Height - 100);

            //根据指定区域得到Graphics

            Graphics g = Graphics.FromImage(image);

            //设置图像的背景色

            g.Clear(this.BackColor);

            //将图像画到Graphics对象中

            DrawMyImage(g);

            try

            {

                //保存画面到Graphics对象中的图形

                image.Save(@"tu1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                g = this.CreateGraphics();

                Rectangle rect = new Rectangle(0, 0, this.Width, this.Height - 100);

                g.FillRectangle(new SolidBrush(this.BackColor), rect);

                MessageBox.Show("保存成功!", "恭喜");

            }

            catch (Exception Err)

            {

                MessageBox.Show(Err.Message);

            }

            image.Dispose();

            g.Dispose();

        }

 

        private void button3_Click(object sender, EventArgs e)

        {

            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height - 100);

            Graphics g = this.CreateGraphics();

            Image image = Image.FromFile(@"tu1.jpg");

            //将图像缩放为指定的大小显示

            g.DrawImage(image, rect);

            image.Dispose();

            g.Dispose();

        }

        private void DrawMyImage(Graphics g)

        {

            Rectangle rect1 = new Rectangle(0, 0, this.Width / 4, this.Height - 100);

            HatchBrush hatchBrush = new HatchBrush(HatchStyle.Shingle, Color.White, Color.Black);

            g.FillEllipse(hatchBrush, rect1);

            Rectangle rect2 = new Rectangle(this.Width / 4 + 50, 0, this.Width / 4, this.Height - 100);

            hatchBrush = new HatchBrush(HatchStyle.WideUpwardDiagonal, Color.White, Color.Red);

            g.FillRectangle(hatchBrush, rect2);

            int x = this.Width - 50 - this.Width / 4;

            Point[] points = new Point[]

            {

                new Point(x,10),

                new Point(x+50,60),

                new Point(x+150,10),

                new Point(x+200,160),

                new Point(x+150,260),

                new Point(x+50,260),

                new Point(x,160)

            };

            hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.White, Color.Red);

            TextureBrush myBrush = new TextureBrush(new Bitmap(@"m23.jpg"));

            g.FillClosedCurve(myBrush, points);

}

1.5   WEB应用程序中的图形图像操作

1.5.1          绘制图形

Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

</head>

<body style="text-align: center">

    <form id="form1" runat="server">

        <iframe id="IFRAME1" runat="server" style="width: 450px; height: 350px"></iframe>

        &nbsp;<br />

        <asp:Button ID="Button1" runat="server" Text="贝塞尔曲线" OnClick="Button1_Click" />

    </form>

</body>

</html>

protected void Button1_Click(object sender, EventArgs e)

    {

        this.IFRAME1.Attributes["src"] = "Default2.aspx";

}

Default2.aspx.cs

protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

        {

            Pen blackPen = new Pen(Color.Red, 3);

            Point[] bezierPoints =

                {

                    new Point(50,100),

                    new Point(100,10),

                    new Point(150,290),

                    new Point(200,100),

                    new Point(250,10),

                    new Point(300,290),

                    new Point(350,100)

                };

            int width = 400;

            int height = 300;

            Bitmap bitmap = new Bitmap(width, height);

            Graphics g = Graphics.FromImage(bitmap);

            g.Clear(Color.White);

            g.DrawBeziers(blackPen, bezierPoints);

            Response.ContentType = "image/gif";

            bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

        }

}

1.5.2          Web图片浏览器

Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div style="text-align: center">

        <asp:Label ID="Label1" runat="server" Text="图片浏览器"></asp:Label><br />

        <iframe style="width: 550px; height: 400px" id="IFRAME1" runat="server"></iframe>

        <br />

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上一个" />

        &nbsp; &nbsp;

        <asp:Button ID="ButtonPosition" runat="server" Text="ButtonPosition" />

        &nbsp; &nbsp;&nbsp;

        <asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="下一个" /></div>

    </form>

</body>

</html>

protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

        {

            Session["index"] = 1;

            this.ButtonPosition.Text = "1 of 8";

            Session["filename"] = Server.MapPath(".") + "\\t1.jpg";

            this.IFRAME1.Attributes["src"] = "Default2.aspx";

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        int index = (int)Session["index"];

        if (index > 1)

        {

            index--;

            this.ButtonPosition.Text = index.ToString() + " of 8";

            Session["index"] = index;

            Session["filename"] = Server.MapPath(".") + @"\t" + index.ToString() + ".jpg";

            this.IFRAME1.Attributes["src"] = "Default2.aspx";

        }

    }

    protected void Button3_Click(object sender, EventArgs e)

    {

        int index = (int)Session["index"];

        if (index < 8)

        {

            index++;

            this.ButtonPosition.Text = index.ToString() + " of 8";

            Session["index"] = index;

            Session["filename"] = Server.MapPath(".") + @"\t" + index.ToString() + ".jpg";

            this.IFRAME1.Attributes["src"] = "Default2.aspx";

        }

}

Default2.aspx.cs

protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

        {

            string filename = (string)Session["filename"];

            Bitmap bitmap = new Bitmap(filename);

            bitmap = new Bitmap(bitmap, 250, 200);

            TextureBrush myBrush = new TextureBrush(bitmap);

            bitmap = new Bitmap(250, 200);

            Graphics g = Graphics.FromImage(bitmap);

            g.Clear(Color.White);

            g.FillEllipse(myBrush, 0, 0, 250, 200);

            Response.ContentType = "image/gif";

            bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

        }

}

1.5.3    当窗体大小改变时如何使图形自动重画

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, Color.Red, Color.Green, LinearGradientMode.Vertical);

            e.Graphics.FillRectangle(brush, this.ClientRectangle);

        }

 

        private void Form1_Resize(object sender, EventArgs e)

        {

            this.Invalidate();

}

1.5.4    特殊效果文字

private void Form1_Paint(object sender, PaintEventArgs e)

        {

            Graphics g = e.Graphics;

            string str = "旋转的文字";

            for (int i = 0; i <= 360; i+=10)

            {

                g.TranslateTransform(150, 150);

                g.RotateTransform(i);

                g.DrawString(str, this.Font, new SolidBrush(Color.Red), 50, 0);

                g.ResetTransform();

            }

            str = "阴影效果的文字";

            g.DrawString(str, new Font("隶书", 35), Brushes.Blue, 250, 30);

            g.DrawString(str, new Font("隶书", 35), new SolidBrush(Color.FromArgb(60, Color.Blue)), 255, 35);

            str = "彩色效果的文字";

            HatchBrush b = new HatchBrush(HatchStyle.Plaid, Color.Blue, Color.Red);

            g.DrawString(str, new Font("黑体", 35), b, 255, 185);

        }

 

 
posted @ 2006-10-19 11:49  '.Elvis.'  阅读(1302)  评论(0编辑  收藏  举报