Пример #1
0
 internal static void SerializeData(CCSize pt, StreamWriter sw)
 {
     sw.WriteLine("{0} {1}", pt.Width, pt.Height);
 }
Пример #2
0
        protected void InitCCLabelBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                         CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(FontConfiguration == null, "re-init is no longer supported");
            Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
                         "Invalid params for CCLabelBMFont");

            if (!String.IsNullOrEmpty(fntFile))
            {
                CCBMFontConfiguration newConf = FNTConfigLoadFile(fntFile);
                if (newConf == null)
                {
                    CCLog.Log("CCLabelBMFont: Impossible to create font. Please check file: '{0}'", fntFile);
                    return;
                }

                FontConfiguration = newConf;

                fntConfigFile = fntFile;

                if (texture == null)
                {
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(FontConfiguration.AtlasName);
                    }
                    catch (Exception)
                    {
                        // Try the 'images' ref location just in case.
                        try
                        {
                            texture =
                                CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
                                                                                                  FontConfiguration
                                                                                                  .AtlasName));
                        }
                        catch (Exception)
                        {
                            // Lastly, try <font_path>/images/<font_name>
                            string dir     = System.IO.Path.GetDirectoryName(FontConfiguration.AtlasName);
                            string fname   = System.IO.Path.GetFileName(FontConfiguration.AtlasName);
                            string newName = System.IO.Path.Combine(System.IO.Path.Combine(dir, "images"), fname);
                            texture = CCTextureCache.SharedTextureCache.AddImage(newName);
                        }
                    }
                }
            }
            else
            {
                texture = new CCTexture2D();
            }

            if (String.IsNullOrEmpty(theString))
            {
                theString = String.Empty;
            }

            TextureAtlas = new CCTextureAtlas(texture, theString.Length);

            this.labelDimensions = dimensions;

            horzAlignment = hAlignment;
            vertAlignment = vAlignment;

            IsOpacityCascaded = true;

            ContentSize = CCSize.Zero;

            IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
            AnchorPoint = CCPoint.AnchorMiddle;

            ImageOffset = imageOffset;

            SetString(theString, true);
        }
Пример #3
0
 public CCLabelTtf(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment) :
     this(text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top)
 {
 }
Пример #4
0
 public CCTLLine()
 {
     glyphRun = new List <LetterInfo>();
     bounds   = CCSize.Zero;
 }
Пример #5
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= (int)contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            var font = CreateFont(textDef.FontName, textDef.FontSize);

            var _currentFontSizeEm = textDef.FontSize;
            var _currentDIP        = ConvertPointSizeToDIP(_currentFontSizeEm);

            var fontColor       = textDef.FontFillColor;
            var fontAlpha       = textDef.FontAlpha;
            var foregroundColor = new Color4(fontColor.R / 255.0f,
                                             fontColor.G / 255.0f,
                                             fontColor.B / 255.0f,
                                             fontAlpha / 255.0f);

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing
                : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center
                : TextAlignment.Leading;

            var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far
                : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center
                : ParagraphAlignment.Near;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap
                : WordWrapping.NoWrap;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }

            var fontName   = font.FontFamily.FamilyNames.GetString(0);
            var textFormat = new TextFormat(FactoryDWrite, fontName,
                                            _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP);

            textFormat.TextAlignment      = textAlign;
            textFormat.ParagraphAlignment = paragraphAlign;

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height);

            var boundingRect = new RectangleF();

            // Loop through all the lines so we can find our drawing offsets
            var textMetrics = textLayout.Metrics;
            var lineCount   = textMetrics.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
            {
                return(new CCTexture2D());
            }

            // Fill out the bounding rect width and height so we can calculate the yOffset later if needed
            boundingRect.X      = 0;
            boundingRect.Y      = 0;
            boundingRect.Width  = textMetrics.Width;
            boundingRect.Height = textMetrics.Height;

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != TextAlignment.Leading)
            {
                textLayout.MaxWidth  = dimensions.Width;
                textLayout.MaxHeight = dimensions.Height;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                      // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                                  // align to center


            SharpDX.WIC.Bitmap sharpBitmap       = null;
            WicRenderTarget    sharpRenderTarget = null;
            SolidColorBrush    solidBrush        = null;

            try
            {
                // Select our pixel format
                var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;

                // create our backing bitmap
                sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                // Create the render target that we will draw to
                sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties());
                // Create our brush to actually draw with
                solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor);

                // Begin the drawing
                sharpRenderTarget.BeginDraw();

                if (textDefinition.isShouldAntialias)
                {
                    sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased;
                }

                // Clear it
                sharpRenderTarget.Clear(TransparentColor);

                // Draw the text to the bitmap
                sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush);

                // End our drawing which will commit the rendertarget to the bitmap
                sharpRenderTarget.EndDraw();

                // Debugging purposes
                //var s = "Label4";
                //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget);

                // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D
                Texture2D tex = null;

                using (var memStream = new MemoryStream())
                {
                    using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream))
                        using (var frameEncoder = new BitmapFrameEncode(encoder))
                        {
                            frameEncoder.Initialize();
                            frameEncoder.WriteSource(sharpBitmap);
                            frameEncoder.Commit();
                            encoder.Commit();
                        }
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream);
                }

                // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it.
                return(new CCTexture2D(tex));
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text.  Message: {0}", exc.StackTrace);
            }
            finally
            {
                if (sharpBitmap != null)
                {
                    sharpBitmap.Dispose();
                    sharpBitmap = null;
                }

                if (sharpRenderTarget != null)
                {
                    sharpRenderTarget.Dispose();
                    sharpRenderTarget = null;
                }

                if (solidBrush != null)
                {
                    solidBrush.Dispose();
                    solidBrush = null;
                }

                if (textFormat != null)
                {
                    textFormat.Dispose();
                    textFormat = null;
                }

                if (textLayout != null)
                {
                    textLayout.Dispose();
                    textLayout = null;
                }
            }

            // If we have reached here then something has gone wrong.
            return(new CCTexture2D());
        }
Пример #6
0
 public CCLayer(CCSize visibleBoundsDimensions,
                CCClipMode clipMode = CCClipMode.None)
     : this(visibleBoundsDimensions, DefaultCameraProjection, clipMode)
 {
 }
Пример #7
0
 public CCSprite(CCSize contentSize, CCSpriteFrame spriteFrame)
 {
     ContentSize = contentSize;
     InitWithSpriteFrame(spriteFrame);
 }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
 /// </summary>
 /// <param name="str">Initial text of the label.</param>
 /// <param name="fntFile">Font definition file to use.</param>
 /// <param name="size">Font point size.</param>
 /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
 /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
 public CCLabel(string str, string fntFile, float size, CCSize dimensions, CCLabelFormat labelFormat)
     : this(str, fntFile, size, dimensions, labelFormat, CCPoint.Zero, null)
 {
 }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
 /// </summary>
 /// <param name="str">Initial text of the label.</param>
 /// <param name="fntFile">Font definition file to use.</param>
 /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
 /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
 /// <param name="imageOffset">Image offset.</param>
 /// <param name="texture">Texture atlas to be used.</param>
 public CCLabel(string str, string fntFile, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture)
 {
     this.labelFormat = labelFormat;
     // First we try loading BitMapFont
     InitBMFont(str, fntFile, dimensions, labelFormat.Alignment, labelFormat.LineAlignment, imageOffset, texture);
 }
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
 /// </summary>
 /// <param name="str">Initial text of the label.</param>
 /// <param name="fntFile">Font definition file to use.</param>
 /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
 /// <param name="hAlignment">Horizontal alignment of the text.</param>
 public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment)
     : this(str, fntFile, dimensions,
            new CCLabelFormat() { Alignment = hAlignment },
            CCPoint.Zero, null)
 {
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
 /// </summary>
 /// <param name="str">Initial text of the label.</param>
 /// <param name="fntFile">Font definition file to use.</param>
 /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
 /// <param name="hAlignment">Horizontal alignment of the text.</param>
 /// <param name="vAlignement">Vertical alignement of the text.</param>
 public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignement)
     : this(str, fntFile, dimensions, hAlignment, vAlignement, CCPoint.Zero, null)
 {
 }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
 /// </summary>
 /// <param name="str">Initial text of the label.</param>
 /// <param name="fntFile">Font definition file to use.</param>
 /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
 public CCLabel(string str, string fntFile, CCSize dimensions)
     : this(str, fntFile, dimensions,
            new CCLabelFormat(), CCPoint.Zero, null)
 {
 }
Пример #13
0
        public override void NeedsLayout()
        {
            if (!parentInited)
            {
                return;
            }
            // Hide the background and the label
            if (titleLabel != null)
            {
                titleLabel.Visible = false;
            }
            if (_backgroundSprite != null)
            {
                _backgroundSprite.Visible = false;
            }
            // Update anchor of all labels
            LabelAnchorPoint = labelAnchorPoint;

            // Update the label to match with the current state

            currentTitle      = GetTitleForState(State);
            currentTitleColor = GetTitleColorForState(State);

            TitleLabel = GetTitleLabelForState(State);

            var label = (ICCTextContainer)titleLabel;

            if (label != null && !String.IsNullOrEmpty(currentTitle))
            {
                label.Text = (currentTitle);
            }

            var rgbaLabel = titleLabel;

            if (rgbaLabel != null)
            {
                rgbaLabel.Color = currentTitleColor;
            }
            if (titleLabel != null)
            {
                titleLabel.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2);
            }

            // Update the background sprite
            BackgroundSprite = GetBackgroundSpriteForState(State);
            if (_backgroundSprite != null)
            {
                _backgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2);
            }

            // Get the title label size
            CCSize titleLabelSize = CCSize.Zero;

            if (titleLabel != null)
            {
                titleLabelSize = titleLabel.BoundingBox.Size;
            }

            // Adjust the background image if necessary
            if (isAdjustBackgroundImage)
            {
                // Add the margins
                if (_backgroundSprite != null)
                {
                    _backgroundSprite.ContentSize = new CCSize(titleLabelSize.Width + _marginH * 2, titleLabelSize.Height + _marginV * 2);
                }
            }
            else
            {
                //TODO: should this also have margins if one of the preferred sizes is relaxed?
                if (_backgroundSprite != null && _backgroundSprite is CCScale9Sprite)
                {
                    CCSize preferredSize = ((CCScale9Sprite)_backgroundSprite).PreferredSize;
                    if (preferredSize.Width <= 0)
                    {
                        preferredSize.Width = titleLabelSize.Width;
                    }
                    if (preferredSize.Height <= 0)
                    {
                        preferredSize.Height = titleLabelSize.Height;
                    }

                    _backgroundSprite.ContentSize = preferredSize;
                }
            }

            // Set the content size
            CCRect rectTitle = CCRect.Zero;

            if (titleLabel != null)
            {
                rectTitle = titleLabel.BoundingBox;
            }
            CCRect rectBackground = CCRect.Zero;

            if (_backgroundSprite != null)
            {
                rectBackground = _backgroundSprite.BoundingBox;
            }

            CCRect maxRect = CCControlUtils.CCRectUnion(rectTitle, rectBackground);

            ContentSize = new CCSize(maxRect.Size.Width, maxRect.Size.Height);

            if (titleLabel != null)
            {
                titleLabel.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2);
                // Make visible label
                titleLabel.Visible = true;
            }

            if (_backgroundSprite != null)
            {
                _backgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2);
                // Make visible the background
                _backgroundSprite.Visible = true;
            }
        }
Пример #14
0
        void LayoutLabel()
        {
            if (FontAtlas == null || string.IsNullOrEmpty(Text))
            {
                ContentSize = CCSize.Zero;
                return;
            }

            TextureAtlas.RemoveAllQuads();
            Descendants.Clear();
            lettersInfo.Clear();

            FontAtlas.PrepareLetterDefinitions(Text);

            var start      = 0;
            var typesetter = new CCTLTextLayout(this);

            var length      = Text.Length;
            var insetBounds = labelDimensions;

            var layoutAvailable = true;

            if (insetBounds == CCSize.Zero)
            {
                insetBounds     = new CCSize(8388608, 8388608);
                layoutAvailable = false;
            }

            var boundsWidth              = insetBounds.Width;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            List <CCTLLine> lineList = new List <CCTLLine>();

            while (start < length)// && textPosition.Y < insetBounds.Bottom)
            {
                // Now we ask the typesetter to break off a line for us.
                // This also will take into account line feeds embedded in the text.
                //  Example: "This is text \n with a line feed embedded inside it"
                int count = typesetter.SuggestLineBreak(start, boundsWidth);
                var line  = typesetter.GetLine(start, start + count);
                lineList.Add(line);

                start += count;
            }


            // Calculate our vertical starting position
            var totalHeight       = lineList.Count * LineHeight;
            var nextFontPositionY = totalHeight;

            if (Dimensions.Height > 0)
            {
                var labelHeightPixel = Dimensions.Height * contentScaleFactorHeight;
                if (totalHeight > labelHeightPixel)
                {
                    int numLines = (int)(labelHeightPixel / LineHeight);
                    totalHeight = numLines * LineHeight;
                }
                switch (VerticalAlignment)
                {
                case CCVerticalTextAlignment.Top:
                    nextFontPositionY = labelHeightPixel;
                    break;

                case CCVerticalTextAlignment.Center:
                    nextFontPositionY = (labelHeightPixel + totalHeight) * 0.5f;
                    break;

                case CCVerticalTextAlignment.Bottom:
                    nextFontPositionY = totalHeight;
                    break;

                default:
                    break;
                }
            }


            var   lineGlyphIndex = 0;
            float longestLine    = (labelDimensions.Width > 0) ? labelDimensions.Width : 0;

            // Used for calculating overlapping on last line character
            var lastCharWidth   = 0.0f;
            int lastCharAdvance = 0;

            // Define our horizontal justification
            var flushFactor = (float)HorizontalAlignment / (float)CCTextAlignment.Right;

            // We now loop through all of our line's glyph runs
            foreach (var line in lineList)
            {
                var gliphRun  = line.GlyphRun;
                var lineWidth = line.Bounds.Width * contentScaleFactorWidth;
                var flush     = line.PenOffsetForFlush(flushFactor, boundsWidth);

                foreach (var glyph in gliphRun)
                {
                    var letterPosition = glyph.Position;
                    var letterDef      = glyph.Definition;
                    lastCharWidth     = letterDef.Width * contentScaleFactorWidth;
                    letterPosition.X += flush;
                    letterPosition.Y  = (nextFontPositionY - letterDef.YOffset) / contentScaleFactorHeight;

                    //recordLetterInfo(letterPosition, glyph.def, lineGlyphIndex++);

                    var tmpInfo = new LetterInfo();

                    tmpInfo.Definition         = letterDef;
                    tmpInfo.Position           = letterPosition;
                    tmpInfo.ContentSize.Width  = letterDef.Width;
                    tmpInfo.ContentSize.Height = letterDef.Height;

                    if (lineGlyphIndex >= lettersInfo.Count)
                    {
                        lettersInfo.Add(tmpInfo);
                    }
                    else
                    {
                        lettersInfo[lineGlyphIndex] = tmpInfo;
                    }

                    lineGlyphIndex++;

                    lastCharAdvance = (int)glyph.Definition.XAdvance;
                }

                // calculate our longest line which is used for calculating our ContentSize
                if (lineWidth > longestLine)
                {
                    longestLine = lineWidth;
                }

                nextFontPositionY -= LineHeight;
            }

            CCSize tmpSize;

            // If the last character processed has an xAdvance which is less that the width of the characters image, then we need
            // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
            // box
            if (lastCharAdvance < lastCharWidth)
            {
                tmpSize.Width = longestLine - lastCharAdvance + lastCharWidth;
            }
            else
            {
                tmpSize.Width = longestLine;
            }

            tmpSize.Height = totalHeight;

            if (Dimensions.Height > 0)
            {
                tmpSize.Height = Dimensions.Height * contentScaleFactorHeight;
            }

            ContentSize = tmpSize / CCLabel.DefaultTexelToContentSizeRatios;

            lineList.Clear();

            CCRect   uvRect;
            CCSprite letterSprite;

            for (int c = 0; c < Children.Count; c++)
            {
                letterSprite = (CCSprite)Children[c];
                int tag = letterSprite.Tag;
                if (tag >= length)
                {
                    RemoveChild(letterSprite, true);
                }
                else if (tag >= 0)
                {
                    if (letterSprite != null)
                    {
                        uvRect = lettersInfo[tag].Definition.Subrect;
                        letterSprite.TextureRectInPixels = uvRect;
                        letterSprite.ContentSize         = uvRect.Size;
                    }
                }
            }

            UpdateQuads();
            UpdateColor();
        }
Пример #15
0
        void LoadAppleDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            var version = dict.ContainsKey("version") ? dict ["version"].AsInt : 0;

            if (version != 1)
            {
                throw (new NotSupportedException("Binary PList version " + version + " is not supported."));
            }


            var images = dict.ContainsKey("images") ? dict ["images"].AsArray : null;

            foreach (var imageEntry in images)
            {
                // we only support one image for now
                var imageDict = imageEntry.AsDictionary;

                var path = imageDict ["path"].AsString;

                path = Path.Combine(plistFilePath, CCFileUtils.RemoveExtension(path));

                if (!CCTextureCache.SharedTextureCache.Contains(path))
                {
                    texture = CCTextureCache.SharedTextureCache.AddImage(path);
                }
                else
                {
                    texture = CCTextureCache.SharedTextureCache[path];
                }



                // size not used right now
                //var size = CCSize.Parse(imageDict ["size"].AsString);

                var subImages = imageDict ["subimages"].AsArray;

                foreach (var subImage in subImages)
                {
                    CCSpriteFrame spriteFrame = null;

                    var subImageDict  = subImage.AsDictionary;
                    var name          = subImageDict ["name"].AsString;
                    var alias         = subImageDict ["alias"].AsString;
                    var isFullyOpaque = true;

                    if (subImageDict.ContainsKey("isFullyOpaque"))
                    {
                        isFullyOpaque = subImageDict ["isFullyOpaque"].AsBool;
                    }

                    var textureRect  = CCRect.Parse(subImageDict ["textureRect"].AsString);
                    var spriteOffset = CCPoint.Parse(subImageDict ["spriteOffset"].AsString);

                    // We are going to override the sprite offset for now to be 0,0
                    // It seems the offset is calculated off of the original size but if
                    // we pass this offset it throws our center position calculations off.
                    spriteOffset = CCPoint.Zero;

                    var textureRotated = false;
                    if (subImageDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = subImageDict ["textureRotated"].AsBool;
                    }
                    var spriteSourceSize = CCSize.Parse(subImageDict ["spriteSourceSize"].AsString);
                    var frameRect        = textureRect;
                    if (textureRotated)
                    {
                        frameRect = new CCRect(textureRect.Origin.X, textureRect.Origin.Y, textureRect.Size.Height, textureRect.Size.Width);
                    }

                    #if DEBUG
                    CCLog.Log("texture {0} rect {1} rotated {2} offset {3}, sourcesize {4}", name, textureRect, textureRotated, spriteOffset, spriteSourceSize);
                    #endif

                    frameRect.Origin += spriteOffset;

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        spriteSourceSize,
                        texture,
                        frameRect,
                        textureRotated
                        );

                    spriteFrame.TextureFilename = name;
                    spriteFrames [name]         = spriteFrame;
                }
            }
            AutoCreateAliasList();
        }
Пример #16
0
        protected void InitBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                  CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(FontConfiguration == null, "re-init is no longer supported");
            Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
                         "Invalid params for CCLabelBMFont");

            if (!String.IsNullOrEmpty(fntFile))
            {
                try
                {
                    FontAtlas = CCFontAtlasCache.GetFontAtlasFNT(fntFile, imageOffset);
                }
                catch {}

                if (FontAtlas == null)
                {
                    CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check file: '{0}'", fntFile);
                    return;
                }
            }

            AnchorPoint = CCPoint.AnchorMiddle;

            FontConfiguration = CCBMFontConfiguration.FontConfigurationWithFile(fntFile);

            LabelType = CCLabelType.BitMapFont;

            if (String.IsNullOrEmpty(theString))
            {
                theString = String.Empty;
            }

            // Initialize the TextureAtlas along with children.
            var capacity = theString.Length;

            BlendFunc = CCBlendFunc.AlphaBlend;

            if (capacity == 0)
            {
                capacity = defaultSpriteBatchCapacity;
            }

            UpdateBlendFunc();

            // no lazy alloc in this node
            Children    = new CCRawList <CCNode>(capacity);
            Descendants = new CCRawList <CCSprite>(capacity);

            this.labelDimensions = dimensions;

            horzAlignment = hAlignment;
            vertAlignment = vAlignment;

            IsOpacityCascaded = true;

            // We use base here so we do not trigger an update internally.
            base.ContentSize = CCSize.Zero;

            IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
            AnchorPoint = CCPoint.AnchorMiddle;

            ImageOffset = imageOffset;

            Text = theString;
        }
Пример #17
0
        void LoadCocos2DDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            PlistDictionary metadataDict = null;

            if (dict.ContainsKey("metadata"))
            {
                metadataDict = dict["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;

            if (dict.ContainsKey("frames"))
            {
                framesDict = dict["frames"].AsDictionary;
            }

            // get the format
            int format = 0;

            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict   = pair.Value.AsDictionary;
                CCSpriteFrame   spriteFrame = null;

                if (format == 0)
                {
                    float x = 0f, y = 0f, w = 0f, h = 0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        new CCSize(ow, oh),
                        texture,
                        new CCRect(x + ox, y + oy, w, h),
                        false
                        );
                }
                else if (format == 1 || format == 2)
                {
                    var  frame   = CCRect.Parse(frameDict["frame"].AsString);
                    bool rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    var offset     = CCPoint.Parse(frameDict["offset"].AsString);
                    var sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

                    frame.Origin += offset;

                    // create frame
                    spriteFrame = new CCSpriteFrame(sourceSize, texture, frame, rotated);
                }
                else if (format == 3)
                {
                    var spriteSize       = CCSize.Parse(frameDict["spriteSize"].AsString);
                    var spriteOffset     = CCPoint.Parse(frameDict["spriteOffset"].AsString);
                    var spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
                    var textureRect      = CCRect.Parse(frameDict["textureRect"].AsString);

                    bool textureRotated = false;

                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    var aliases = frameDict["aliases"].AsArray;

                    for (int i = 0; i < aliases.Count; i++)
                    {
                        string oneAlias = aliases[i].AsString;

                        if (spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            if (spriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("CocosSharp: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }

                        if (!spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            spriteFramesAliases.Add(oneAlias, pair.Key);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        spriteSourceSize,
                        texture,
                        new CCRect(textureRect.Origin.X + spriteOffset.X, textureRect.Origin.Y + spriteOffset.Y, spriteSize.Width, spriteSize.Height),
                        textureRotated
                        );
                }

                spriteFrame.TextureFilename = pair.Key;
                spriteFrames[pair.Key]      = spriteFrame;
            }
            AutoCreateAliasList();
        }
Пример #18
0
        protected void InitSpriteFont(string theString, string fntFile, float fontSize, CCSize dimensions, CCLabelFormat labelFormat,
                                      CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
                         "Invalid params for CCLabel SpriteFont");

            if (!String.IsNullOrEmpty(fntFile))
            {
                try
                {
                    FontAtlas = CCFontAtlasCache.GetFontAtlasSpriteFont(fntFile, fontSize, imageOffset);
                    Scale     = FontAtlas.Font.FontScale;
                }
                catch {}

                if (FontAtlas == null)
                {
                    CCLog.Log("SpriteFont CCLabel: Impossible to create font. Please check file: '{0}'", fntFile);
                    return;
                }
            }

            AnchorPoint = CCPoint.AnchorMiddle;

            LabelType = CCLabelType.SpriteFont;

            if (String.IsNullOrEmpty(theString))
            {
                theString = String.Empty;
            }

            // Initialize the TextureAtlas along with children.
            var capacity = theString.Length;

            BlendFunc = CCBlendFunc.AlphaBlend;

            if (capacity == 0)
            {
                capacity = defaultSpriteBatchCapacity;
            }

            UpdateBlendFunc();

            // no lazy alloc in this node
            Children    = new CCRawList <CCNode>(capacity);
            Descendants = new CCRawList <CCSprite>(capacity);

            this.labelDimensions = dimensions;

            horzAlignment = labelFormat.Alignment;
            vertAlignment = labelFormat.LineAlignment;

            IsOpacityCascaded = true;

            ContentSize = CCSize.Zero;

            IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
            AnchorPoint = CCPoint.AnchorMiddle;

            ImageOffset = imageOffset;

            Text = theString;
        }
Пример #19
0
 public CCLayer(CCSize visibleBoundsDimensions,
                CCCameraProjection cameraProjection,
                CCClipMode clipMode = CCClipMode.None)
     : this(new CCCamera(cameraProjection, visibleBoundsDimensions), clipMode)
 {
 }
Пример #20
0
 public static CCPhysicsBody CreateBox(CCSize size, float radius)
 {
     return(CreateBox(size, CCPhysicsMaterial.PHYSICSSHAPE_MATERIAL_DEFAULT, radius));
 }
Пример #21
0
 public CCTransitionSceneContainerNode(CCScene scene, CCSize contentSize) : base(contentSize)
 {
     InnerScene = scene;
 }
Пример #22
0
 public static CCPhysicsBody CreateEdgeBox(CCSize size, float border, CCPoint offset)
 {
     return(CreateEdgeBox(size, CCPhysicsMaterial.PHYSICSSHAPE_MATERIAL_DEFAULT, border, offset));
 }
Пример #23
0
        public bool UpdateWithBatchNode(CCSpriteBatchNode batchnode, CCRect rect, bool rotated, CCRect capInsets)
        {
            var opacity = Opacity;
            var color   = Color;

            // Release old sprites
            RemoveAllChildren(true);

            scale9Image = batchnode;
            scale9Image.RemoveAllChildren(true);

            this.capInsets     = capInsets;
            spriteFrameRotated = rotated;

            // If there is no given rect
            if (rect.Equals(CCRect.Zero))
            {
                // Get the texture size as original
                CCSize textureSize = scale9Image.TextureAtlas.Texture.ContentSizeInPixels;

                rect = new CCRect(0, 0, textureSize.Width, textureSize.Height);
            }

            // Set the given rect's size as original size
            spriteRect        = rect;
            originalSize      = rect.Size;
            preferredSize     = originalSize;
            capInsetsInternal = capInsets;

            float h = rect.Size.Height;
            float w = rect.Size.Width;

            // If there is no specified center region
            if (capInsetsInternal.Equals(CCRect.Zero))
            {
                capInsetsInternal = new CCRect(w / 3, h / 3, w / 3, h / 3);
            }

            float left_w   = capInsetsInternal.Origin.X;
            float center_w = capInsetsInternal.Size.Width;
            float right_w  = rect.Size.Width - (left_w + center_w);

            float top_h    = capInsetsInternal.Origin.Y;
            float center_h = capInsetsInternal.Size.Height;
            float bottom_h = rect.Size.Height - (top_h + center_h);

            // calculate rects

            // ... top row
            float x = 0.0f;
            float y = 0.0f;

            // top left
            CCRect lefttopbounds = new CCRect(x, y, left_w, top_h);

            // top center
            x += left_w;
            CCRect centertopbounds = new CCRect(x, y, center_w, top_h);

            // top right
            x += center_w;
            CCRect righttopbounds = new CCRect(x, y, right_w, top_h);

            // ... center row
            x  = 0.0f;
            y  = 0.0f;
            y += top_h;

            // center left
            CCRect leftcenterbounds = new CCRect(x, y, left_w, center_h);

            // center center
            x += left_w;
            CCRect centerbounds = new CCRect(x, y, center_w, center_h);

            // center right
            x += center_w;
            CCRect rightcenterbounds = new CCRect(x, y, right_w, center_h);

            // ... bottom row
            x  = 0.0f;
            y  = 0.0f;
            y += top_h;
            y += center_h;

            // bottom left
            CCRect leftbottombounds = new CCRect(x, y, left_w, bottom_h);

            // bottom center
            x += left_w;
            CCRect centerbottombounds = new CCRect(x, y, center_w, bottom_h);

            // bottom right
            x += center_w;
            CCRect rightbottombounds = new CCRect(x, y, right_w, bottom_h);

            if (!rotated)
            {
                CCAffineTransform t = CCAffineTransform.Identity;
                t = CCAffineTransform.Translate(t, rect.Origin.X, rect.Origin.Y);

                centerbounds       = CCAffineTransform.Transform(centerbounds, t);
                rightbottombounds  = CCAffineTransform.Transform(rightbottombounds, t);
                leftbottombounds   = CCAffineTransform.Transform(leftbottombounds, t);
                righttopbounds     = CCAffineTransform.Transform(righttopbounds, t);
                lefttopbounds      = CCAffineTransform.Transform(lefttopbounds, t);
                rightcenterbounds  = CCAffineTransform.Transform(rightcenterbounds, t);
                leftcenterbounds   = CCAffineTransform.Transform(leftcenterbounds, t);
                centerbottombounds = CCAffineTransform.Transform(centerbottombounds, t);
                centertopbounds    = CCAffineTransform.Transform(centertopbounds, t);

                // Centre
                centre = new CCSprite(scale9Image.Texture, centerbounds);
                scale9Image.AddChild(centre, 0, (int)Positions.Centre);

                // Top
                top = new CCSprite(scale9Image.Texture, centertopbounds);
                scale9Image.AddChild(top, 1, (int)Positions.Top);

                // Bottom
                bottom = new CCSprite(scale9Image.Texture, centerbottombounds);
                scale9Image.AddChild(bottom, 1, (int)Positions.Bottom);

                // Left
                left = new CCSprite(scale9Image.Texture, leftcenterbounds);
                scale9Image.AddChild(left, 1, (int)Positions.Left);

                // Right
                right = new CCSprite(scale9Image.Texture, rightcenterbounds);
                scale9Image.AddChild(right, 1, (int)Positions.Right);

                // Top left
                topLeft = new CCSprite(scale9Image.Texture, lefttopbounds);
                scale9Image.AddChild(topLeft, 2, (int)Positions.TopLeft);

                // Top right
                topRight = new CCSprite(scale9Image.Texture, righttopbounds);
                scale9Image.AddChild(topRight, 2, (int)Positions.TopRight);

                // Bottom left
                bottomLeft = new CCSprite(scale9Image.Texture, leftbottombounds);
                scale9Image.AddChild(bottomLeft, 2, (int)Positions.BottomLeft);

                // Bottom right
                bottomRight = new CCSprite(scale9Image.Texture, rightbottombounds);
                scale9Image.AddChild(bottomRight, 2, (int)Positions.BottomRight);
            }
            else
            {
                // set up transformation of coordinates
                // to handle the case where the sprite is stored rotated
                // in the spritesheet
                // CCLog("rotated");

                CCAffineTransform t = CCAffineTransform.Identity;

                CCRect rotatedcenterbounds       = centerbounds;
                CCRect rotatedrightbottombounds  = rightbottombounds;
                CCRect rotatedleftbottombounds   = leftbottombounds;
                CCRect rotatedrighttopbounds     = righttopbounds;
                CCRect rotatedlefttopbounds      = lefttopbounds;
                CCRect rotatedrightcenterbounds  = rightcenterbounds;
                CCRect rotatedleftcenterbounds   = leftcenterbounds;
                CCRect rotatedcenterbottombounds = centerbottombounds;
                CCRect rotatedcentertopbounds    = centertopbounds;

                t = CCAffineTransform.Translate(t, rect.Size.Height + rect.Origin.X, rect.Origin.Y);
                t = CCAffineTransform.Rotate(t, 1.57079633f);

                centerbounds       = CCAffineTransform.Transform(centerbounds, t);
                rightbottombounds  = CCAffineTransform.Transform(rightbottombounds, t);
                leftbottombounds   = CCAffineTransform.Transform(leftbottombounds, t);
                righttopbounds     = CCAffineTransform.Transform(righttopbounds, t);
                lefttopbounds      = CCAffineTransform.Transform(lefttopbounds, t);
                rightcenterbounds  = CCAffineTransform.Transform(rightcenterbounds, t);
                leftcenterbounds   = CCAffineTransform.Transform(leftcenterbounds, t);
                centerbottombounds = CCAffineTransform.Transform(centerbottombounds, t);
                centertopbounds    = CCAffineTransform.Transform(centertopbounds, t);

                rotatedcenterbounds.Origin       = centerbounds.Origin;
                rotatedrightbottombounds.Origin  = rightbottombounds.Origin;
                rotatedleftbottombounds.Origin   = leftbottombounds.Origin;
                rotatedrighttopbounds.Origin     = righttopbounds.Origin;
                rotatedlefttopbounds.Origin      = lefttopbounds.Origin;
                rotatedrightcenterbounds.Origin  = rightcenterbounds.Origin;
                rotatedleftcenterbounds.Origin   = leftcenterbounds.Origin;
                rotatedcenterbottombounds.Origin = centerbottombounds.Origin;
                rotatedcentertopbounds.Origin    = centertopbounds.Origin;

                // Centre
                centre = new CCSprite(scale9Image.Texture, rotatedcenterbounds, true);
                //centre.InitWithTexture(scale9Image.Texture, rotatedcenterbounds, true);
                scale9Image.AddChild(centre, 0, (int)Positions.Centre);

                // Top
                top = new CCSprite(scale9Image.Texture, rotatedcentertopbounds, true);
                //top.InitWithTexture(scale9Image.Texture, rotatedcentertopbounds, true);
                scale9Image.AddChild(top, 1, (int)Positions.Top);

                // Bottom
                bottom = new CCSprite(scale9Image.Texture, rotatedcenterbottombounds, true);
                //bottom.InitWithTexture(scale9Image.Texture, rotatedcenterbottombounds, true);
                scale9Image.AddChild(bottom, 1, (int)Positions.Bottom);

                // Left
                left = new CCSprite(scale9Image.Texture, rotatedleftcenterbounds, true);
                //left.InitWithTexture(scale9Image.Texture, rotatedleftcenterbounds, true);
                scale9Image.AddChild(left, 1, (int)Positions.Left);

                // Right
                right = new CCSprite(scale9Image.Texture, rotatedrightcenterbounds, true);
                //right.InitWithTexture(scale9Image.Texture, rotatedrightcenterbounds, true);
                scale9Image.AddChild(right, 1, (int)Positions.Right);

                // Top left
                topLeft = new CCSprite(scale9Image.Texture, rotatedlefttopbounds, true);
                //topLeft.InitWithTexture(scale9Image.Texture, rotatedlefttopbounds, true);
                scale9Image.AddChild(topLeft, 2, (int)Positions.TopLeft);

                // Top right
                topRight = new CCSprite(scale9Image.Texture, rotatedrighttopbounds, true);
                //topRight.InitWithTexture(scale9Image.Texture, rotatedrighttopbounds, true);
                scale9Image.AddChild(topRight, 2, (int)Positions.TopRight);

                // Bottom left
                bottomLeft = new CCSprite(scale9Image.Texture, rotatedleftbottombounds, true);
                //bottomLeft.InitWithTexture(scale9Image.Texture, rotatedleftbottombounds, true);
                scale9Image.AddChild(bottomLeft, 2, (int)Positions.BottomLeft);

                // Bottom right
                bottomRight = new CCSprite(scale9Image.Texture, rotatedrightbottombounds, true);
                //bottomRight.InitWithTexture(scale9Image.Texture, rotatedrightbottombounds, true);
                scale9Image.AddChild(bottomRight, 2, (int)Positions.BottomRight);
            }

            ContentSize = rect.Size;
            AddChild(scale9Image);

            if (spritesGenerated)
            {
                // Restore color and opacity
                Opacity = opacity;
                Color   = color;
            }
            spritesGenerated = true;

            return(true);
        }
Пример #24
0
        public void AlignItemsInColumns(params uint[] numOfItemsPerRow)
        {
            alignmentState.Alignment        = Alignment.Column;
            alignmentState.NumberOfItemsPer = numOfItemsPerRow;

            float height          = -DefaultPadding;
            int   row             = 0;
            int   rowHeight       = 0;
            int   columnsOccupied = 0;
            uint  rowColumns;

            if (menuItems != null && menuItems.Count > 0)
            {
                foreach (CCMenuItem item in menuItems)
                {
                    if (item.Visible)
                    {
                        Debug.Assert(row < numOfItemsPerRow.Length);

                        rowColumns = numOfItemsPerRow[row];
                        // can not have zero columns on a row
                        Debug.Assert(rowColumns > 0, "");

                        float tmp = item.ContentSize.Height;
                        rowHeight = (int)((rowHeight >= tmp || float.IsNaN(tmp)) ? rowHeight : tmp);

                        ++columnsOccupied;
                        if (columnsOccupied >= rowColumns)
                        {
                            height += rowHeight + (int)DefaultPadding;

                            columnsOccupied = 0;
                            rowHeight       = 0;
                            ++row;
                        }
                    }
                }

                // check if too many rows/columns for available menu items
                Debug.Assert(columnsOccupied == 0, "");

                CCSize menuSize = ContentSize;

                row        = 0;
                rowHeight  = 0;
                rowColumns = 0;
                float w = 0.0f;
                float x = 0.0f;
                float y = (height / 2f);

                foreach (CCMenuItem item in menuItems)
                {
                    if (item.Visible)
                    {
                        if (rowColumns == 0)
                        {
                            rowColumns = numOfItemsPerRow[row];
                            if (rowColumns == 0)
                            {
                                throw (new ArgumentException("Can not have a zero column size for a row."));
                            }
                            w = (menuSize.Width - 2 * DefaultPadding) / rowColumns; // 1 + rowColumns
                            x = w / 2f;                                             // center of column
                        }

                        float tmp = item.ContentSize.Height * item.ScaleY;
                        rowHeight = (int)((rowHeight >= tmp || float.IsNaN(tmp)) ? rowHeight : tmp);

                        item.Position
                            = new CCPoint(DefaultPadding + x - (menuSize.Width - 2 * DefaultPadding) / 2,
                                          y - item.ContentSize.Height * item.ScaleY / 2);

                        x += w;
                        ++columnsOccupied;

                        if (columnsOccupied >= rowColumns)
                        {
                            y -= rowHeight + DefaultPadding;

                            columnsOccupied = 0;
                            rowColumns      = 0;
                            rowHeight       = 0;
                            ++row;
                        }
                    }
                }
            }
        }
Пример #25
0
 public CCLabelBMFont(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                      CCPoint imageOffset, CCTexture2D texture)
 {
     InitCCLabelBMFont(str, fntFile, dimensions, hAlignment, vAlignment, imageOffset, texture);
 }
Пример #26
0
        public void AlignItemsInRows(params uint[] numOfItemsPerColumn)
        {
            alignmentState.Alignment        = Alignment.Row;
            alignmentState.NumberOfItemsPer = numOfItemsPerColumn;

            List <float> columnWidths  = new List <float>();
            List <float> columnHeights = new List <float>();

            float width        = -DefaultPadding * 2.0f;
            float columnHeight = -DefaultPadding;
            int   column       = 0;
            int   columnWidth  = 0;
            int   rowsOccupied = 0;
            uint  columnRows;

            if (menuItems != null && menuItems.Count > 0)
            {
                foreach (CCMenuItem item in menuItems)
                {
                    if (item.Visible)
                    {
                        // check if too many menu items for the amount of rows/columns
                        Debug.Assert(column < numOfItemsPerColumn.Length, "");

                        columnRows = numOfItemsPerColumn[column];
                        // can't have zero rows on a column
                        Debug.Assert(columnRows > 0, "");

                        float tmp = item.ContentSize.Width * item.ScaleX;
                        columnWidth = (int)((columnWidth >= tmp || float.IsNaN(tmp)) ? columnWidth : tmp);


                        columnHeight += (int)(item.ContentSize.Height * item.ScaleY + DefaultPadding);
                        ++rowsOccupied;

                        if (rowsOccupied >= columnRows)
                        {
                            columnWidths.Add(columnWidth);
                            columnHeights.Add(columnHeight);
                            width += columnWidth + DefaultPadding * 2.0f;

                            rowsOccupied = 0;
                            columnWidth  = 0;
                            columnHeight = -DefaultPadding;
                            ++column;
                        }
                    }
                }

                // check if too many rows/columns for available menu items.
                Debug.Assert(rowsOccupied == 0, "");

                CCSize menuSize = ContentSize;

                column      = 0;
                columnWidth = 0;
                columnRows  = 0;
                float x = (-width / 2f);
                float y = 0.0f;

                foreach (CCMenuItem item in menuItems)
                {
                    if (item.Visible)
                    {
                        if (columnRows == 0)
                        {
                            columnRows = numOfItemsPerColumn[column];
                            y          = columnHeights [column];
                        }

                        // columnWidth = fmaxf(columnWidth, [item contentSize].width);
                        float tmp = item.ContentSize.Width * item.ScaleX;
                        columnWidth = (int)((columnWidth >= tmp || float.IsNaN(tmp)) ? columnWidth : tmp);

                        item.Position = new CCPoint(x + columnWidths [column] / 2, y - menuSize.Height / 2);
                        y            -= item.ContentSize.Height * item.ScaleY + 10;
                        ++rowsOccupied;

                        if (rowsOccupied >= columnRows)
                        {
                            x           += columnWidth + 5;
                            rowsOccupied = 0;
                            columnRows   = 0;
                            columnWidth  = 0;
                            ++column;
                        }
                    }
                }
            }
        }
Пример #27
0
        public void CreateFontChars()
        {
            int  nextFontPositionX = 0;
            int  nextFontPositionY = 0;
            char prev          = (char)255;
            int  kerningAmount = 0;

            CCSize tmpSize = CCSize.Zero;

            int longestLine = 0;
            int totalHeight = 0;

            int quantityOfLines = 1;

            if (String.IsNullOrEmpty(labelText))
            {
                return;
            }

            int stringLen = labelText.Length;

            var charSet = FontConfiguration.CharacterSet;

            if (charSet.Count == 0)
            {
                throw (new InvalidOperationException(
                           "Can not compute the size of the font because the character set is empty."));
            }

            for (int i = 0; i < stringLen - 1; ++i)
            {
                if (labelText[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            LineHeight = FontConfiguration.CommonHeight;

            totalHeight       = LineHeight * quantityOfLines;
            nextFontPositionY = 0 -
                                (LineHeight - LineHeight * quantityOfLines);

            CCBMFontConfiguration.CCBMGlyphDef fontDef = null;
            CCRect fontCharTextureRect;
            CCSize fontCharContentSize;

            for (int i = 0; i < stringLen; i++)
            {
                char c = labelText[i];

                if (c == '\n')
                {
                    nextFontPositionX  = 0;
                    nextFontPositionY -= LineHeight;
                    continue;
                }

                if (charSet.IndexOf(c) == -1)
                {
                    CCLog.Log("CocosSharp: CCLabelBMFont: Attempted to use character not defined in this bitmap: {0}",
                              (int)c);
                    continue;
                }

                kerningAmount = this.KerningAmountForFirst(prev, c);

                // unichar is a short, and an int is needed on HASH_FIND_INT
                if (!FontConfiguration.Glyphs.TryGetValue(c, out fontDef))
                {
                    CCLog.Log("CocosSharp: CCLabelBMFont: character not found {0}", (int)c);
                    continue;
                }

                fontCharTextureRect           = fontDef.Subrect;
                fontCharTextureRect.Origin.X += ImageOffset.X;
                fontCharTextureRect.Origin.Y += ImageOffset.Y;

                fontCharContentSize = fontCharTextureRect.Size / DefaultTexelToContentSizeRatios;

                CCSprite fontChar;

                //bool hasSprite = true;
                fontChar = (CCSprite)(this[i]);
                if (fontChar != null)
                {
                    // Reusing previous Sprite
                    fontChar.Visible = true;

                    // updating previous sprite
                    fontChar.IsTextureRectRotated = false;
                    fontChar.ContentSize          = fontCharContentSize;
                    fontChar.TextureRectInPixels  = fontCharTextureRect;
                }
                else
                {
                    // New Sprite ? Set correct color, opacity, etc...
                    //if( false )
                    //{
                    //    /* WIP: Doesn't support many features yet.
                    //     But this code is super fast. It doesn't create any sprite.
                    //     Ideal for big labels.
                    //     */
                    //    fontChar = m_pReusedChar;
                    //    fontChar.BatchNode = null;
                    //    hasSprite = false;
                    //}
                    //else
                    {
                        fontChar             = new CCSprite(TextureAtlas.Texture, fontCharTextureRect);
                        fontChar.ContentSize = fontCharContentSize;
                        AddChild(fontChar, i, i);
                    }

                    // Apply label properties
                    fontChar.IsColorModifiedByOpacity = IsColorModifiedByOpacity;

                    // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
                    fontChar.UpdateDisplayedColor(DisplayedColor);
                    fontChar.UpdateDisplayedOpacity(DisplayedOpacity);
                }

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = FontConfiguration.CommonHeight - fontDef.YOffset;

                var fontPos =
                    new CCPoint(
                        (float)nextFontPositionX + fontDef.XOffset + fontDef.Subrect.Size.Width * 0.5f + kerningAmount,
                        (float)nextFontPositionY + yOffset - fontCharTextureRect.Size.Height * 0.5f);

                fontChar.Position = fontPos;

                // update kerning
                nextFontPositionX += fontDef.XAdvance + kerningAmount;
                prev = c;

                if (longestLine < nextFontPositionX)
                {
                    longestLine = nextFontPositionX;
                }
            }

            // If the last character processed has an xAdvance which is less that the width of the characters image, then we need
            // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
            // box
            if (fontDef != null && fontDef.XAdvance < fontDef.Subrect.Size.Width)
            {
                tmpSize.Width = longestLine + fontDef.Subrect.Size.Width - fontDef.XAdvance;
            }
            else
            {
                tmpSize.Width = longestLine;
            }

            tmpSize.Height = totalHeight;
            var tmpDimensions = labelDimensions;

            labelDimensions = new CCSize(
                labelDimensions.Width > 0 ? labelDimensions.Width : tmpSize.Width,
                labelDimensions.Height > 0 ? labelDimensions.Height : tmpSize.Height
                );

            ContentSize     = labelDimensions;
            labelDimensions = tmpDimensions;
        }
Пример #28
0
 public void SetDesignResolutionSize(float width, float height, CCSceneResolutionPolicy resolutionPolicy)
 {
     designResolutionSize   = new CCSize(width, height);
     DesignResolutionPolicy = resolutionPolicy;
 }
Пример #29
0
 public CCLabelTtf(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment)
 {
     InitCCLabelTTF(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
 }
Пример #30
0
        internal void AddSpriteFrames(PlistDictionary pobDictionary, CCTexture2D pobTexture)
        {
            /*
             * Supported Zwoptex Formats:
             *
             * ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
             * ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
             * ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
             * ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
             */

            PlistDictionary metadataDict = null;

            if (pobDictionary.ContainsKey("metadata"))
            {
                metadataDict = pobDictionary["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;

            if (pobDictionary.ContainsKey("frames"))
            {
                framesDict = pobDictionary["frames"].AsDictionary;
            }

            int format = 0;

            // get the format
            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict   = pair.Value.AsDictionary;
                CCSpriteFrame   spriteFrame = null;

                if (format == 0)
                {
                    float x = 0f, y = 0f, w = 0f, h = 0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);
                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        new CCSize(ow, oh),
                        pobTexture,
                        new CCRect(x, y, w, h),
                        new CCSize(ow, oh),
                        false,
                        new CCPoint(ox, oy)
                        );
                }
                else if (format == 1 || format == 2)
                {
                    CCRect frame   = CCRect.Parse(frameDict["frame"].AsString);
                    bool   rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    CCPoint offset     = CCPoint.Parse(frameDict["offset"].AsString);
                    CCSize  sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        sourceSize,
                        pobTexture,
                        frame,
                        sourceSize,
                        rotated,
                        offset
                        );
                }
                else if (format == 3)
                {
                    // get values
                    CCSize  spriteSize       = CCSize.Parse(frameDict["spriteSize"].AsString);
                    CCPoint spriteOffset     = CCPoint.Parse(frameDict["spriteOffset"].AsString);
                    CCSize  spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
                    CCRect  textureRect      = CCRect.Parse(frameDict["textureRect"].AsString);
                    bool    textureRotated   = false;
                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    PlistArray aliases  = frameDict["aliases"].AsArray;
                    string     frameKey = pair.Key;

                    foreach (PlistObjectBase item2 in aliases)
                    {
                        string oneAlias = item2.AsString;
                        if (spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            if (spriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("CocosSharp: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }
                        if (!spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            spriteFramesAliases.Add(oneAlias, frameKey);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        spriteSourceSize,
                        pobTexture,
                        new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
                        spriteSourceSize,
                        textureRotated,
                        spriteOffset
                        );
                }

                // add sprite frame
                string key = pair.Key;
                if (!AllowFrameOverwrite && spriteFrames.ContainsKey(key))
                {
                    CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
                }
                else if (AllowFrameOverwrite || !spriteFrames.ContainsKey(key))
                {
                    spriteFrames[key] = spriteFrame;
                }
            }
        }