public static Canvas LoadComponent(string xaml) { XElement x = XElement.Parse(xaml); XElement xRoot = x.Elements().FirstOrDefault(); Canvas canvas = null; if (xRoot.Name.LocalName == "Canvas") { canvas = new Canvas() { Name = xRoot.SafeGetName(), Width = xRoot.SafeGetFloat("Width"), Height = xRoot.SafeGetFloat("Height") }; canvas.ContentSize = new CCSize(canvas.Width, canvas.Height); var eList = xRoot.Elements().ToList(); foreach (var e in eList) { switch (e.Name.LocalName) { case "Image": { if (e.Attribute("Source") != null) { string filename = e.Attribute("Source").Value; Image image = new Image(Factory.CreateSpriteFrame(filename)) { Name = e.SafeGetName() }; image.Width = e.SafeGetFloat("Width"); image.Height = e.SafeGetFloat("Height"); image.Left = e.SafeGetFloat("Canvas.Left"); image.Top = e.SafeGetFloat("Canvas.Top"); image.Visible = (e.SafeGetText("Visibility") != "Collapsed"); if (e.Attribute("Opacity") != null) image.Opacity = (byte)(255 * e.SafeGetFloat("Opacity")); canvas.AddChild(image); } } break; case "TextBlock": { string fontFamily = e.SafeGetText("FontFamily"); if (fontFamily == "") { //fontFamily = "Content/font.fnt"; continue; } TextBlock textblock = new TextBlock(fontFamily, e.SafeGetText("Text"), e.SafeGetFloat("FontSize")) { Name = e.SafeGetName() }; textblock.Left = e.SafeGetFloat("Canvas.Left"); textblock.Top = e.SafeGetFloat("Canvas.Top"); textblock.Visible = (e.SafeGetText("Visibility") != "Collapsed"); if (e.Attribute("Opacity") != null) textblock.Opacity = (byte)(255 * e.SafeGetFloat("Opacity")); if (e.Attribute("Foreground") != null) { CCColor4B color = Colors.Parse(e.SafeGetText("Foreground")); textblock.Color = new CCColor3B(color.R, color.G, color.B); } canvas.AddChild(textblock); } break; } } } canvas.ArrangeChild(); return canvas; }
//锚点以元素的左下角为准(0,0) public static Canvas CreateListLayer(CCNode[] nodes, float marginLeft, float marginTop, float marginBottom, float marginRight) { float layerWidth = 0; float layerHeight = 0; foreach (CCNode node in nodes) { float nodeWidth = node.ContentSize.Width + marginLeft + marginRight; float nodeHeight = node.ContentSize.Height + marginTop + marginBottom; if (nodeWidth > layerWidth) layerWidth = nodeWidth; layerHeight += nodeHeight; } Canvas canvas = new Canvas() { ContentSize = new CCSize(layerWidth, layerHeight) }; //CCLayerColor color = new CCLayerColor(CCColor4B.Yellow, layerWidth, layerHeight); //canvas.AddChild(color); float posX = marginLeft; float posY = 0; for (int i = 0; i < nodes.Length; i++) { posY += (nodes[i].ContentSize.Height + marginTop); nodes[i].PositionX = posX; nodes[i].PositionY = layerHeight - posY; posY += marginBottom; canvas.AddChild(nodes[i]); } return canvas; }