前面几篇介绍了如何使用graphics绘制图像,这几篇准备介绍如何使用graphics提供的方法绘制统计图。
包括:柱状图、折线图、饼图。
假设知道某个公司1-4季度的盈利情况,我们来看看如何完成统计图
新建一个窗体,
添加4个标签,分别是“一季度”、“二季度”、“三季度”、“四季度”
添加4个numericupdown,名称从 nudsesson1 至 nudsesson4
添加4个按钮,名称为btnBarGraph、btnLineChart、btnPie、btnSave,对应Text属性为 柱状图、折线图、饼图、保存
图示如下:
以柱状图为例,目前考虑的步骤:
1、创建graphics对象
2、绘制坐标轴
3、绘制立柱
4、显示出来
新建窗体级变量:
Dim g As Graphics Dim bmp As Bitmap
在窗体载入的时候将bmp、g实例化,bmp的大小根据实际需要建立:
Private Sub Form7_Load(sender As Object,e As EventArgs) Handles MyBase.Load bmp = New Bitmap(600,350) g = Graphics.FromImage(bmp) End Sub
当按下“柱状图”按钮的时候调用三个函数,分别是绘制坐标轴、绘制立柱、显示到窗口:
Private Sub btnDraw_Click(sender As Object,e As EventArgs) Handles btnBarGraph.Click Call DrawAxis() Call DrawBarGraph() Call DrawToForm() End Sub
'绘制坐标轴 Private Sub DrawAxis() '使用红色绘制坐标轴 Dim p As New Pen(Color.Red,1) '坐标轴末尾箭头 p.EndCap = Drawing2D.LineCap.ArrowAnchor '坐标原点 Dim originX As Integer = 40 Dim originY As Integer = 320 Dim originPoint As Point = New Point(originX,originY) '绘制横坐标 g.DrawLine(p,originPoint,New Point(540,320)) '绘制纵坐标--http://blog.csdn.net/uruseibest g.DrawLine(p,New Point(40,20)) '红色绘制坐标轴刻度 Dim pAxisY As New Pen(Color.Red,1) Dim AxisYPos As Point Dim AxisYValue As String '在纵轴上标明刻度线,从0-90,每10个刻度标注一下 '注意的是,我们使用了1:3的比例 For i As Integer = 0 To 9 '刻度值 AxisYValue = (i * 10).ToString '刻度位置 AxisYPos = New Point(20,originY - i * 30 - 5) '标明刻度值 g.DrawString(AxisYValue,New Font("宋体",10),New SolidBrush(Color.Blue),AxisYPos) '画刻度,实际0刻度线是和横坐标轴重合 g.DrawLine(pAxisY,originY - i * 30),New Point(50,originY - i * 30)) Next End Sub
'绘制立柱 Private Sub DrawBarGraph() '标注每个季度 Dim seasonValue(3) As Integer seasonValue(0) = nudSeason1.Value seasonValue(1) = nudSeason2.Value seasonValue(2) = nudSeason3.Value seasonValue(3) = nudSeason4.Value Dim seasonName() As String = {"一季度","二季度","三季度","四季度"} '立柱(矩形)的左上角坐标点 Dim recX,recY As Integer '循环画四个矩形--http://blog.csdn.net/uruseibest For i As Integer = 0 To 3 recX = (i + 1) * 80 '注意:我们的坐标轴是按照1:3绘制,所有这里需要*3 recY = 320 - seasonValue(i) * 3 g.FillRectangle(New SolidBrush(Color.Blue),New Rectangle(recX,recY,40,seasonValue(i) * 3)) Next '标出每个季度 Dim strX,strY As Integer For i As Integer = 0 To 3 strX = (i + 1) * 80 - 5 strY = 325 g.DrawString(seasonName(i),New Font("黑体",New Point(strX,strY)) Next End Sub
'将bmp绘制到窗体表面 Private Sub DrawToForm() Dim g1 As Graphics = Me.CreateGraphics g1.DrawImage(bmp,New Point(0,0)) End Sub
当按下“柱状图”按钮时,如下图所示:
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256733.html