7.2.1 制图原理
就像在第 4 章中,当我们画饼图时,我们将使用标准 .NET 的 System.Drawin 库。此示例的点是演示使用以前表示,绘图是极其简单,所以,在清单 7.6 的核心函数只有几行代码。它遍历列表中的所有元素,包含绘制的代码在两个不同的元素。
Listing 7.6 Drawing document using flat representation (F# Interactive)
> let drawElements elements (gr:Graphics) =
for p in elements do
match p with
| TextElement(text, boundingBox) –>
let boxf = toRectangleF(boundingBox)
gr.DrawString(text.Text, text.Font, Brushes.Black, boxf)
| ImageElement(imagePath, boundingBox) –>
let bmp = new Bitmap(imagePath)
let wspace, hspace =
boundingBox.Width / 10.0f, boundingBox.Height / 10.0f
let rc = toRectangleF(deflate(boundingBox, wspace, hspace))
gr.DrawImage(bmp, rc);;
val drawElements : seq -> Graphics –> unit
该函数绘制给定的图形对象指定元素的列表。第一个参数的类型是 seq ,表示包含 ScreenElement 类型值的任何集合。到目前为止,我们已经处理过列表,但在第 10 和 12 章,将会看到一些其他集合 (如数组)。在代码中,我们只需要用 for 循环遍历集合中的元素,这样 ,编译器为我们推断出一般类型。类型 seq <'a> 对应于泛型 IEnumerable,所以,在 C# 中的参数类型可能是 IEnumerable。
这个代码还使用了前一节处理 Rect 值的函数。我们使用 toRectangleF 转换 Rect 值到 DrawString 方法需要的类型,deflate 增加图像周围的空间。
我们的绘图函数取图形对象作为参数值,所以,我们需要用某种方法来创建一个。作为最后一步,我们将写一些代码来创建窗体,把文档绘制上去。