---
title: ".Net Micro Framework研究—Shapes命名空间"
author: "mmdev"
date: "2007-11-06T14:37:00Z"
tags: []
slug: "net-micro-framework-shapes"
draft: false
lastmod: "2012-08-04T21:32:58Z"
id: 1620945
url: "https://mmdev.iteye.com/blog/1620945"
---

试验平台：.Net Micro Framework 模拟器

在Microsoft.SPOT.Presentation.Shapes命名空间下，包含几个形状对象，主要有Ellipse、Line、Polygon、Rectangle，同样也只有Rectangle实现的最好，其他形状都不支持填充色，虽然每个对象都有Fill属性。

让人奇怪的是，每个形状对象都不能设置left和top坐标，仅能设置宽度和高度，用起来很不习惯。

StackPanel类是Panel的派生类，从字面意思上看，就是可以堆叠的面板。意如其名，它可以包含多个子对象，不过每一对象都不能重叠，以特有的方式堆叠在一起。

有如下几个属性方法控制堆叠方式：

1、 Orientation属性，有两种方式：Orientation.Horizontal，Orientation.Vertical。设置该属性后，StackPanel的子对象的坐标系就会发生变化（很可惜字体的方向并没有从根本上改变）。

2、 HorizontalAlignment、VerticalAlignment属性，设置子对象的堆叠方式。枚举定义如下。

public enum HorizontalAlignment

{

Left = 0,

Center = 1,

Right = 2,

Stretch = 3,

}

public enum VerticalAlignment

{

Top = 0,

Center = 1,

Bottom = 2,

Stretch = 3,

}

3、 SetMargin方法，设置边界空白大小。

完整的代码如下，

using System;

using Microsoft.SPOT;

using Microsoft.SPOT.Input;

using Microsoft.SPOT.Presentation;

using Microsoft.SPOT.Presentation.Controls;

using Microsoft.SPOT.Presentation.Media;

using Microsoft.SPOT.Presentation.Shapes;

namespace MFWindow

{

public class Program : Microsoft.SPOT.Application

{

public static void Main()

{

//创建窗体

WindowsDrawing win = new WindowsDrawing();

//程序运行

new Program().Run(win);

}

internal sealed class WindowsDrawing : Window

{

public WindowsDrawing()

{

this.Width = SystemMetrics.ScreenWidth;

this.Height = SystemMetrics.ScreenHeight;

//可设置显示方向（水平，垂直）

//StackPanel panel = new StackPanel(Orientation.Vertical);

StackPanel panel = new StackPanel(Orientation.Horizontal);

//设置边界空白

panel.SetMargin(10);

//设置对象堆叠的方式

panel.HorizontalAlignment = HorizontalAlignment.Center;

panel.VerticalAlignment = VerticalAlignment.Center;

this.Child = panel;

//添加文本

Text txt = new Text(Resources.GetFont(Resources.FontResources.small), "yefan");

//不能设置left,top坐标

txt.Width = 100;

txt.Height = 30;

panel.Children.Add(txt);

//添加不同的形状对象

Shape\[] shapes = new Shape\[]

{

new Ellipse(),

new Line(),

new Polygon(new Int32\[] { 0, 0, 10, 0, 10, 10, 0, 10 }),

new Rectangle()

};

//设置形状对象必要的参数(各对象不能重叠，只能堆叠在一起)

foreach (Shape s in shapes)

{

s.Fill = new SolidColorBrush(ColorUtility.ColorFromRGB(0, 255, 0));

s.Stroke = new Pen(Color.Black, 2);

//不能设置left,top坐标

s.Height = 40;

s.Width = 40;

panel.Children.Add(s);

}

}

}

}

}

仅修改这句代码 StackPanel panel = new StackPanel(Orientation.Horizontal);中的参数就可以实现两种不同的效果，如下面两图所示：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/yefanqiu/MF071106001.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/yefanqiu/MF071106002.jpg)

总的来说，我觉得MF提供的图像对象还很不完善，不仅一些基本功能没有完成（如填充、线宽），并且无法设置形状对象的绝对坐标（left,top），同时总类也特别少，希望以后的版本中能有很大的提升。