实验目标:
- 掌握C#图形绘制基本概念;
- 掌握C#字体处理;
- 能进行C#图形图像综合设计。
核心功能:
- 使用pen绘制基础图形;
- 使用LinearGradientBrush实现渐变色字体;
- 使用GraphicsPath实现艺术字。
代码实现:
功能1:
设计界面添加button。
private void button1_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics(); //创建Graphics对象
Pen myPen = new Pen(Color.Blue, 2); //创建Pen对象
graphics.DrawEllipse(myPen, 80, 150, 100, 50); //绘制椭圆
graphics.DrawRectangle(myPen, 80, 150, 100, 50); //绘制矩形
}
通过 Graphics 类中的 DrawEllipse 方法可以轻松地绘制椭圆。该方法可以绘制由一对坐标、高度和宽度指定的椭圆。 语法如下:
public void DrawEllipse(Pen pen,int x,int y,int width,int height)
矩形绘制(DrawRectangle)同理 。
功能2:
using System.Drawing.Drawing2D;
private void button1_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Pen myPen = new Pen(Color.Blue, 2);
graphics.DrawEllipse(myPen, 80, 150, 100, 50);
graphics.DrawRectangle(myPen, 80, 150, 100, 50);
Font font = new Font("微软雅黑", 20);
string str = "大家学会了吗???"; //设置字符串
SizeF size = graphics.MeasureString(str, font); //获取字符串的尺寸
PointF point = new PointF(80, 50);
RectangleF rect = new RectangleF(point, size); //字符串显示的区域
LinearGradientBrush linearBrush = new LinearGradientBrush(rect,
Color.GreenYellow, Color.OrangeRed, LinearGradientMode.Horizontal); //创建笔刷
graphics.DrawString(str, font, linearBrush, point); //绘制文本
}
LinearGradientBrush(Rectangle, Color, Color, LinearGradientMode)
功能3:
private void button2_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Pen myPen = new Pen(Color.Blue, 2);
/*下面即老师所给的核心代码,稍作修改
GraphicsPath gp = new GraphicsPath(FillMode.Winding);
gp.AddString(
"字体轮廓",new FontFamily("方正舒体"),(int)FontStyle.Regular,
80,new PointF(10, 20),new StringFormat());
Brush brush = XXXXXXXXXXXXXXXXXXXXXX;
XXX.DrawPath(Pens.Green, gp);
XXX.FillPath(brush, gp);
*/
GraphicsPath gp = new GraphicsPath(FillMode.Winding);
gp.AddString(
this.textBox1.Text, new FontFamily("方正舒体"), (int)FontStyle.Regular,
50, new PointF(250, 150), new StringFormat());
//text Box1.Text的值就是用户输入的字符串
Brush brush = Brushes.OrangeRed;
graphics.DrawPath(Pens.Green, gp);
graphics.FillPath(brush, gp);
}
AddString(String, FontFamily, Int32, Single, PointF, StringFormat)
结果展示:
相关参考: