Ejemplo n.º 1
1
        internal static CCTexture2D CreateNativeLabel(string text, CCSize dimensions, CCTextAlignment hAlignment,
		                                   CCVerticalTextAlignment vAlignment, string fontName,
		                                   float fontSize, CCColor4B textColor)
		{

		    if (string.IsNullOrEmpty(text))
		    {
		        return new CCTexture2D();
		    }

		    var font = CreateFont (fontName, fontSize);

            if (dimensions.Equals(CCSize.Zero))
            {
                CreateBitmap(1, 1);

                var ms = _graphics.MeasureString(text, font);
                
                dimensions.Width = ms.Width;
                dimensions.Height = ms.Height;
            }

            CreateBitmap((int)dimensions.Width, (int)dimensions.Height);

            var stringFormat = new StringFormat();

		    switch (hAlignment)
		    {
		        case CCTextAlignment.Left:
                    stringFormat.Alignment = StringAlignment.Near;
		            break;
		        case CCTextAlignment.Center:
                    stringFormat.Alignment = StringAlignment.Center;
		            break;
		        case CCTextAlignment.Right:
                    stringFormat.Alignment = StringAlignment.Far;
		            break;
		    }

		    switch (vAlignment)
		    {
		        case CCVerticalTextAlignment.Top:
        		    stringFormat.LineAlignment = StringAlignment.Near;
		            break;
		        case CCVerticalTextAlignment.Center:
        		    stringFormat.LineAlignment = StringAlignment.Center;
		            break;
		        case CCVerticalTextAlignment.Bottom:
        		    stringFormat.LineAlignment = StringAlignment.Far;
		            break;
		    }

            _graphics.DrawString(text, font, _brush, new RectangleF(0, 0, dimensions.Width, dimensions.Height), stringFormat);
            _graphics.Flush();

			var texture = new CCTexture2D();
			texture.InitWithStream (SaveToStream(), Microsoft.Xna.Framework.Graphics.SurfaceFormat.Bgra4444);

			return texture;
		}
Ejemplo n.º 2
0
 public bool InitWithTarget(Action<CCMenuItem> selector, CCMenuItem[] items)
 {
     base.InitWithTarget(selector);
     CascadeColorEnabled = true;
     CascadeOpacityEnabled = true;
     m_pSubItems = new List<CCMenuItem>();
     float w = float.MinValue;
     float h = float.MinValue;
     foreach (CCMenuItem item in items)
     {
         m_pSubItems.Add(item);
         AddChild(item, 0);
         item.Visible = false;
         if (w < item.ContentSize.Width)
         {
             w = item.ContentSize.Width;
         }
         if (h < item.ContentSize.Height)
         {
             h = item.ContentSize.Height;
         }
         item.AnchorPoint = CCPoint.AnchorMiddle;
     }
     ContentSize = new CCSize(w, h);
     foreach (CCMenuItem item in items)
     {
         item.Position = ContentSize.Center;
     }
     m_uSelectedIndex = int.MaxValue;
     SelectedIndex = 0;
     return true;
 }
Ejemplo n.º 3
0
 public void updateSize(CCPoint touchLocation)
 {
     CCSize s = CCDirector.SharedDirector.WinSize;
     CCSize newSize = new CCSize(Math.Abs(touchLocation.X - s.Width / 2) * 2, Math.Abs(touchLocation.Y - s.Height / 2) * 2);
     CCLayerColor l = (CCLayerColor)GetChildByTag(kTagLayer);
     l.ContentSize = newSize;
 }
Ejemplo n.º 4
0
        public static CCMenuItem CreateScaledMenuItemLabel(CCSize buttonSize, int labelPadding, float strokeSize, CCColor3B textColor, CCColor3B strokeColor, CCColor3B backColor, string labelText, Action action)
        {
            var menuItem = action != null ? new CCMenuItem(o => action()) : new CCMenuItem();

            var labelSize = new CCSize(buttonSize.Width - labelPadding, buttonSize.Height - labelPadding);

            // Add background
            var blockSprite = new CCSprite("images/Block_Back");
            blockSprite.ScaleTo(buttonSize);
            blockSprite.Color = backColor;

            menuItem.AddChild(blockSprite);
            menuItem.ContentSize = buttonSize;

            // Add label
            var labelTtf = new CCLabelTTF(labelText, "arial-24", 10);
            labelTtf.Color = textColor;

            // Add Stroke to label
            // if (strokeSize > 0) labelTtf.AddStroke(strokeSize, strokeColor);

            if (labelTtf.ContentSize.Width > labelSize.Width)
            {
                labelTtf.ScaleTo(labelSize);
            }

            menuItem.AddChild(labelTtf);

            return menuItem;
        }
Ejemplo n.º 5
0
 public static CCSize Transform(CCSize size, CCAffineTransform t)
 {
     var s = new CCSize();
     s.Width = (float) ((double) t.a * size.Width + (double) t.c * size.Height);
     s.Height = (float) ((double) t.b * size.Width + (double) t.d * size.Height);
     return s;
 }
Ejemplo n.º 6
0
        /// <summary>
        ///  Implement CCDirector and CCScene init code here.
        /// </summary>
        /// <returns>
        ///  true  Initialize success, app continue.
        ///  false Initialize failed, app terminate.
        /// </returns>
        public override bool ApplicationDidFinishLaunching()
        {
            //initialize director
            CCDirector pDirector = CCDirector.SharedDirector;
            pDirector.SetOpenGlView();

            CCSpriteFontCache.RegisterFont("arial", 12, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 50, 64);
            CCSpriteFontCache.RegisterFont("MarkerFelt", 16, 18, 22);
            CCSpriteFontCache.RegisterFont("MarkerFelt-Thin", 12, 18);
            CCSpriteFontCache.RegisterFont("Paint Boy", 26);
            CCSpriteFontCache.RegisterFont("Schwarzwald Regular", 26);
            CCSpriteFontCache.RegisterFont("Scissor Cuts", 26);
            CCSpriteFontCache.RegisterFont("A Damn Mess", 26);
            CCSpriteFontCache.RegisterFont("Abberancy", 26);
            CCSpriteFontCache.RegisterFont("Abduction", 26);

            // turn on display FPS
            pDirector.DisplayStats = true;
            // set FPS. the default value is 1.0/60 if you don't call this
            pDirector.AnimationInterval = 1.0 / 60;

            CCSize designSize = new CCSize(480, 320);

            if (CCDrawManager.FrameSize.Height > 320)
            {
                CCSize resourceSize = new CCSize(960, 640);
                CCContentManager.SharedContentManager.SearchPaths.Add("hd");
                pDirector.ContentScaleFactor = resourceSize.Height / designSize.Height;
            }

            CCDrawManager.SetDesignResolutionSize(designSize.Width, designSize.Height, CCResolutionPolicy.ShowAll);

/*
#if WINDOWS || WINDOWSGL
            CCDrawManager.SetDesignResolutionSize(1280, 768, CCResolutionPolicy.ExactFit);
#else
            CCDrawManager.SetDesignResolutionSize(800, 480, CCResolutionPolicy.ShowAll);
            //CCDrawManager.SetDesignResolutionSize(480, 320, CCResolutionPolicy.ShowAll);
#endif
*/

            // create a scene. it's an autorelease object
            CCScene pScene = new CCScene();
            CCLayer pLayer = new TestController();
            
            /*           
            CCScene pScene = CCScene.node();
            var pLayer = Box2DView.viewWithEntryID(0);
            pLayer.scale = 10;
            pLayer.anchorPoint = new CCPoint(0, 0);
            pLayer.position = new CCPoint(CCDirector.sharedDirector().getWinSize().width / 2, CCDirector.sharedDirector().getWinSize().height / 4);
            */

            pScene.AddChild(pLayer);
            pDirector.RunWithScene(pScene);

            return true;
        }
Ejemplo n.º 7
0
 public LCC3GraphicsTexture(int tag, string name)
     : base(tag, name)
 {
     _size = new LCC3IntSize(0, 0);
     _coverage = CCSize.Zero;
     _hasMipmap = false;
     _isFlippedVertically = true;
     _hasPremultipliedAlpha = false;
     this.TextureParameters = this.DefaultTextureParameters;
 }
Ejemplo n.º 8
0
 protected override void OnHandlePropTypeSize(CCNode node, CCNode parent, string propertyName, CCSize pSize, CCBReader reader)
 {
     if (propertyName == PROPERTY_CONTENTSIZE)
     {
         ((CCScrollView) node).ViewSize = pSize;
     }
     else
     {
         base.OnHandlePropTypeSize(node, parent, propertyName, pSize, reader);
     }
 }
Ejemplo n.º 9
0
        public bool InitWithTileFile(string tile, string mapFile, int tileWidth, int tileHeight)
        {
            LoadTgAfile(mapFile);
            CalculateItemsToRender();

            if (base.InitWithTileFile(tile, tileWidth, tileHeight, m_nItemsToRender))
            {
                m_pPosToAtlasIndex = new Dictionary<CCGridSize, int>();
                UpdateAtlasValues();
                ContentSize = new CCSize(m_pTGAInfo.width * m_uItemWidth, m_pTGAInfo.height * m_uItemHeight);
                return true;
            }
            return false;
        }
Ejemplo n.º 10
0
		public static CCSize CCSizeFromString(string pszContent)
		{
			CCSize ret = new CCSize();
			
			do
			{
				List<string> strs = new List<string>();
				if (!CCUtils.SplitWithForm(pszContent, strs)) break;
				
				float width = CCUtils.CCParseFloat(strs[0]);
				float height = CCUtils.CCParseFloat(strs[1]);
				
				ret = new CCSize(width, height);
			} while (false);
			
			return ret;
		}
Ejemplo n.º 11
0
        private CCSize _winSize; // Contains the dimensions of the game window

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Creates a new instance of an enemy using the Enemy content and mask.
        /// </summary>
        public Enemy()
            : base(GameObjectType.Enemy, "Images/Enemy", "Enemy")
        {
            // Create a new instance of the shots list
            _shots = new List<GameObject>();

            // Get the dimensions of the window
            _winSize = CCDirector.SharedDirector.WinSize;

            // Set the speed of the enemy
            _speed = CollisionGame.Rand.Next(2, 7);

            // Get the next time that a shot will be fired
            _nextShot = CollisionGame.Rand.Next(2, 5);

            // Tell Cocos2d-XNA to schedule a call to this sprite's Update method
            ScheduleUpdate();
        }
Ejemplo n.º 12
0
        private void updateAlignment()
        {
            var blockSize = new CCSize(200, 160);
            CCSize s = CCDirector.SharedDirector.WinSize;

            if (m_plabel != null)
            {
                m_plabel.RemoveFromParentAndCleanup(true);
            }

            m_plabel = new CCLabelTTF(getCurrentAlignment(), "Marker Felt", 32,
                                         blockSize, m_eHorizAlign, m_eVertAlign);

            m_plabel.AnchorPoint = new CCPoint(0, 0);
            m_plabel.Position = new CCPoint((s.Width - blockSize.Width) / 2, (s.Height - blockSize.Height) / 2);

            AddChild(m_plabel);
        }
Ejemplo n.º 13
0
        public static CCPoint GetAbsolutePosition(CCPoint pt, CCBPositionType nType, CCSize containerSize, string pPropName)
        {
            CCPoint absPt = new CCPoint(0, 0);
            
            if (nType == CCBPositionType.RelativeBottomLeft)
            {
                absPt = pt;
            }
            else if (nType == CCBPositionType.RelativeTopLeft)
            {
                absPt.X = pt.X;
                absPt.Y = containerSize.Height - pt.Y;
            }
            else if (nType == CCBPositionType.RelativeTopRight)
            {
                absPt.X = containerSize.Width - pt.X;
                absPt.Y = containerSize.Height - pt.Y;
            }
            else if (nType == CCBPositionType.RelativeBottomRight)
            {
                absPt.X = containerSize.Width - pt.X;
                absPt.Y = pt.Y;
            }
            else if (nType == CCBPositionType.Percent)
            {
                absPt.X = (int) (containerSize.Width * pt.X / 100.0f);
                absPt.Y = (int) (containerSize.Height * pt.Y / 100.0f);
            }
            else if (nType == CCBPositionType.MultiplyResolution)
            {
                float resolutionScale = CCBReader.ResolutionScale;

                absPt.X = pt.X * resolutionScale;
                absPt.Y = pt.Y * resolutionScale;
            }

            return absPt;
        }
Ejemplo n.º 14
0
        public LabelTTFTest()
        {
            var blockSize = new CCSize(200, 160);
            CCSize s = CCDirector.SharedDirector.WinSize;

            CCLayerColor colorLayer = new CCLayerColor(new CCColor4B(100, 100, 100, 255), blockSize.Width, blockSize.Height);
            colorLayer.AnchorPoint = new CCPoint(0, 0);
            colorLayer.Position = new CCPoint((s.Width - blockSize.Width) / 2, (s.Height - blockSize.Height) / 2);

            AddChild(colorLayer);

            CCMenuItemFont.FontSize = 30;
            CCMenu menu = new CCMenu(
                new CCMenuItemFont("Left", setAlignmentLeft),
                new CCMenuItemFont("Center", setAlignmentCenter),
                new CCMenuItemFont("Right", setAlignmentRight)
                );
            menu.AlignItemsVerticallyWithPadding(4);
            menu.Position = new CCPoint(50, s.Height / 2 - 20);
            AddChild(menu);

            menu = new CCMenu(
                new CCMenuItemFont("Top", setAlignmentTop),
                new CCMenuItemFont("Middle", setAlignmentMiddle),
                new CCMenuItemFont("Bottom", setAlignmentBottom)
                );
            menu.AlignItemsVerticallyWithPadding(4);
            menu.Position = new CCPoint(s.Width - 50, s.Height / 2 - 20);
            AddChild(menu);

            m_plabel = null;
            m_eHorizAlign = CCTextAlignment.CCTextAlignmentLeft;
            m_eVertAlign = CCVerticalTextAlignment.CCVerticalTextAlignmentTop;

            updateAlignment();
        }
Ejemplo n.º 15
0
 public bool InitWithString(string label, string fontName, float fontSize, CCSize dimensions, CCTextAlignment alignment)
 {
     return InitWithString(label, fontName, fontSize, dimensions, alignment, CCVerticalTextAlignment.Top);
 }
Ejemplo n.º 16
0
        public CCNode ReadNodeGraphFromData(byte[] bytes, object owner, CCSize parentSize)
        {
            _bytes = bytes;
            _currentByte = 0;
            _currentBit = 0;
            _owner = owner;

            _actionManager.RootContainerSize = parentSize;
            _actionManager._owner = _owner;
            _ownerOutletNodes = new List<CCNode>();
            _ownerCallbackNodes = new List<CCNode>();

            Dictionary<CCNode, CCBAnimationManager> animationManagers = new Dictionary<CCNode, CCBAnimationManager>();
            CCNode pNodeGraph = ReadFileWithCleanUp(true, animationManagers);

            if (pNodeGraph != null && _actionManager.AutoPlaySequenceId != -1 && !_jsControlled)
            {
                // Auto play animations
                _actionManager.RunAnimationsForSequenceIdTweenDuration(_actionManager.AutoPlaySequenceId, 0);
            }
            // Assign actionManagers to userObject
            if (_jsControlled)
            {
                _nodesWithAnimationManagers = new List<CCNode>();
                _animationManagersForNodes = new List<CCBAnimationManager>();
            }

            foreach (var pElement in animationManagers)
            {
                CCNode pNode = pElement.Key;
                CCBAnimationManager manager = animationManagers[pNode];
                pNode.UserObject = manager;

                if (_jsControlled)
                {
                    _nodesWithAnimationManagers.Add(pNode);
                    _animationManagersForNodes.Add(manager);
                }
            }

            return pNodeGraph;
        }
Ejemplo n.º 17
0
        protected virtual bool InitWithString(string theString, string fntFile, CCSize dimentions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                              CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(m_pConfiguration == 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 false;
                }

                m_pConfiguration = newConf;

                m_sFntFile = fntFile;

                if (texture == null)
                {
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
                    }
                    catch (Exception)
                    {
                        // Try the 'images' ref location just in case.
                        try
                        {
                            texture =
                                CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
                                                                                                  m_pConfiguration
                                                                                                      .AtlasName));
                        }
                        catch (Exception)
                        {
                            // Lastly, try <font_path>/images/<font_name>
                            string dir = System.IO.Path.GetDirectoryName(m_pConfiguration.AtlasName);
                            string fname = System.IO.Path.GetFileName(m_pConfiguration.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;
            }

            if (base.InitWithTexture(texture, theString.Length))
            {
                m_tDimensions = dimentions;

                m_pHAlignment = hAlignment;
                m_pVAlignment = vAlignment;

                m_cDisplayedOpacity = m_cRealOpacity = 255;
                m_tDisplayedColor = m_tRealColor = CCTypes.CCWhite;
                m_bCascadeOpacityEnabled = true;
                m_bCascadeColorEnabled = true;

                m_obContentSize = CCSize.Zero;

                m_bIsOpacityModifyRGB = m_pobTextureAtlas.Texture.HasPremultipliedAlpha;
                AnchorPoint = new CCPoint(0.5f, 0.5f);

                m_tImageOffset = imageOffset;

                m_pReusedChar = new CCSprite();
                m_pReusedChar.InitWithTexture(m_pobTextureAtlas.Texture, CCRect.Zero, false);
                m_pReusedChar.BatchNode = this;

                SetString(theString, true);

                return true;
            }
            return false;
        }
Ejemplo n.º 18
0
 public CCRect(CCSize sz)
 {
     Origin = CCPoint.Zero;
     Size   = sz;
 }
Ejemplo n.º 19
0
        public void AlignItemsHorizontallyWithPadding(float padding)
        {
            float height = 0f;
            float width = -padding;
            if (m_pChildren != null && m_pChildren.count > 0)
            {
                for (int i = 0, count = m_pChildren.count; i < count; i++)
                {
                    CCNode pChild = m_pChildren[i];
                    if (pChild.Visible)
                    {
                        width += pChild.ContentSize.Width * pChild.ScaleX + padding;
                        height = Math.Max(height, pChild.ContentSize.Height * pChild.ScaleY);
                    }
                }
            }

            float x = -width / 2.0f;

            if (m_pChildren != null && m_pChildren.count > 0)
            {
                for (int i = 0, count = m_pChildren.count; i < count; i++)
                {
                    CCNode pChild = m_pChildren[i];
                    if (pChild.Visible)
                    {
                        pChild.Position = new CCPoint(x + pChild.ContentSize.Width * pChild.ScaleX / 2.0f, 0);
                        x += pChild.ContentSize.Width * pChild.ScaleX + padding;
                        height = Math.Max(height, pChild.ContentSize.Height * pChild.ScaleY);
                    }
                }
            }
            ContentSize = new CCSize(width, height);
        }
Ejemplo n.º 20
0
 public bool UpdateWithBatchNode(CCSpriteBatchNode batchnode, CCSize bounds, bool rotated, CCRect capInsets)
 {
     return(UpdateWithBatchNode(batchnode, bounds.AsRect, rotated, capInsets));
 }
Ejemplo n.º 21
0
        private 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(
                        texture,
                        new CCRect(x, y, w, h),
                        false,
                        new CCPoint(ox, oy),
                        new CCSize(ow, oh)
                        );
                }
                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);

                    // create frame
                    spriteFrame = new CCSpriteFrame(texture, frame, rotated, offset, sourceSize);
                }
                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("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }

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

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

                _spriteFrames[pair.Key] = spriteFrame;
            }
        }
Ejemplo n.º 22
0
		public void showFont(string pFont)
		{
			CCSize s = CCDirector.SharedDirector.WinSize;

			var blockSize = new CCSize(s.Width / 3, 200);
			float fontSize = 26;

			RemoveChildByTag(kTagLabel1, true);
			RemoveChildByTag(kTagLabel2, true);
			RemoveChildByTag(kTagLabel3, true);
			RemoveChildByTag(kTagLabel4, true);


			var top = new CCLabel(pFont,"Arial", 24);

			var left = new CCLabel("alignment left", pFont, fontSize,
			                                 blockSize, CCTextAlignment.Left,
			                                 SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);
			var center = new CCLabel("alignment center", pFont, fontSize,
			                                   blockSize, CCTextAlignment.Center,
			                                   SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);
			var right = new CCLabel("alignment right", pFont, fontSize,
			                                  blockSize, CCTextAlignment.Right,
			                                  SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);

            top.AnchorPoint = CCPoint.AnchorMiddleBottom;
            left.AnchorPoint = CCPoint.AnchorMiddle;// new CCPoint(0, 0.5f);
			center.AnchorPoint = CCPoint.AnchorMiddle;
            right.AnchorPoint = CCPoint.AnchorMiddle;

            float yMax = s.Height / 2f + 50f;
			top.Position = new CCPoint(s.Width / 2f, s.Height - 20f);
			left.Position = new CCPoint(s.Width/3f, yMax - 50);
			center.Position = new CCPoint(s.Width/2f, yMax - 50);
			right.Position = new CCPoint(s.Width * 2f/3f, yMax - 50);

			AddChild(left, 3, kTagLabel1);
			AddChild(right, 3, kTagLabel2);
			AddChild(center, 3, kTagLabel3);
			AddChild(top, 3, kTagLabel4);
		}
Ejemplo n.º 23
0
 public CCSpriteFrame(CCTexture2D pobTexture, CCRect rect, bool rotated, CCPoint offset,
                      CCSize originalSize)
 {
     InitWithTexture(pobTexture, rect, rotated, offset, originalSize);
 }
Ejemplo n.º 24
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(m_sString))
            {
                return;
            }

            int stringLen = m_sString.Length;

            var charSet = m_pConfiguration.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 (m_sString[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            totalHeight       = m_pConfiguration.m_nCommonHeight * quantityOfLines;
            nextFontPositionY = 0 -
                                (m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);

            CCBMFontConfiguration.CCBMFontDef fontDef = null;
            CCRect rect;

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

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

                if (charSet.IndexOf(c) == -1)
                {
                    CCLog.Log("Cocos2D.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 (!m_pConfiguration.m_pFontDefDictionary.TryGetValue(c, out fontDef))
                {
                    CCLog.Log("cocos2d::CCLabelBMFont: characer not found {0}", (int)c);
                    continue;
                }

                rect = fontDef.rect;
                rect = CCMacros.CCRectanglePixelsToPoints(rect);

                rect.Origin.X += m_tImageOffset.X;
                rect.Origin.Y += m_tImageOffset.Y;

                CCSprite fontChar;

                //bool hasSprite = true;
                fontChar = (CCSprite)(GetChildByTag(i));
                if (fontChar != null)
                {
                    // Reusing previous Sprite
                    fontChar.Visible = true;
                }
                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();
                        fontChar.InitWithTexture(m_pobTextureAtlas.Texture, rect);
                        AddChild(fontChar, i, i);
                    }

                    // Apply label properties
                    fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;

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

                // updating previous sprite
                fontChar.SetTextureRect(rect, false, rect.Size);

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
                var fontPos =
                    new CCPoint(
                        (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
                        (float)nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
                fontChar.Position = CCMacros.CCPointPixelsToPoints(fontPos);

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

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

                //if (! hasSprite)
                //{
                //  UpdateQuadFromSprite(fontChar, i);
                //}
            }

            // 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.xAdvance < fontDef.rect.Size.Width)
            {
                tmpSize.Width = longestLine + fontDef.rect.Size.Width - fontDef.xAdvance;
            }
            else
            {
                tmpSize.Width = longestLine;
            }
            tmpSize.Height = totalHeight;

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

            ContentSize = CCMacros.CCSizePixelsToPoints(tmpSize);
        }
Ejemplo n.º 25
0
 public CCGrid3D(CCGridSize gridSize, CCSize size)
 {
     InitWithSize(gridSize, size);
 }
Ejemplo n.º 26
0
        protected virtual bool InitWithString(string theString, string fntFile, CCSize dimentions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                              CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(m_pConfiguration == 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(false);
                }

                m_pConfiguration = newConf;

                m_sFntFile = fntFile;

                if (texture == null)
                {
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
                    }
                    catch (Exception)
                    {
                        // Try the 'images' ref location just in case.
                        try
                        {
                            texture =
                                CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
                                                                                                  m_pConfiguration
                                                                                                  .AtlasName));
                        }
                        catch (Exception)
                        {
                            // Lastly, try <font_path>/images/<font_name>
                            string dir     = System.IO.Path.GetDirectoryName(m_pConfiguration.AtlasName);
                            string fname   = System.IO.Path.GetFileName(m_pConfiguration.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;
            }

            if (base.InitWithTexture(texture, theString.Length))
            {
                m_tDimensions = dimentions;

                m_pHAlignment = hAlignment;
                m_pVAlignment = vAlignment;

                m_cDisplayedOpacity      = m_cRealOpacity = 255;
                m_tDisplayedColor        = m_tRealColor = CCTypes.CCWhite;
                m_bCascadeOpacityEnabled = true;
                m_bCascadeColorEnabled   = true;

                m_obContentSize = CCSize.Zero;

                m_bIsOpacityModifyRGB = m_pobTextureAtlas.Texture.HasPremultipliedAlpha;
                AnchorPoint           = new CCPoint(0.5f, 0.5f);

                m_tImageOffset = imageOffset;

                m_pReusedChar = new CCSprite();
                m_pReusedChar.InitWithTexture(m_pobTextureAtlas.Texture, CCRect.Zero, false);
                m_pReusedChar.BatchNode = this;

                SetString(theString, true);

                return(true);
            }
            return(false);
        }
Ejemplo n.º 27
0
        public bool InitWithString(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment)
        {
            InitializeFont(fontName, fontSize, text);

            return(base.InitWithString(text, GetFontKey(fontName, fontSize), dimensions, hAlignment, vAlignment, CCPoint.Zero, m_pTexture));
        }
Ejemplo n.º 28
0
        public bool UpdateWithBatchNode(CCSpriteBatchNode batchnode, CCRect rect, bool rotated, CCRect capInsets)
        {
            var opacity = Opacity;
            var color   = Color;

            // Release old sprites
            RemoveAllChildrenWithCleanup(true);

            _scale9Image = batchnode;
            _scale9Image.RemoveAllChildrenWithCleanup(true);

            _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.ContentSize;

                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)
            {
                // CCLog("!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();
                _centre.InitWithTexture(_scale9Image.Texture, centerbounds);
                _scale9Image.AddChild(_centre, 0, (int)Positions.Centre);

                // Top
                _top = new CCSprite();
                _top.InitWithTexture(_scale9Image.Texture, centertopbounds);
                _scale9Image.AddChild(_top, 1, (int)Positions.Top);

                // Bottom
                _bottom = new CCSprite();
                _bottom.InitWithTexture(_scale9Image.Texture, centerbottombounds);
                _scale9Image.AddChild(_bottom, 1, (int)Positions.Bottom);

                // Left
                _left = new CCSprite();
                _left.InitWithTexture(_scale9Image.Texture, leftcenterbounds);
                _scale9Image.AddChild(_left, 1, (int)Positions.Left);

                // Right
                _right = new CCSprite();
                _right.InitWithTexture(_scale9Image.Texture, rightcenterbounds);
                _scale9Image.AddChild(_right, 1, (int)Positions.Right);

                // Top left
                _topLeft = new CCSprite();
                _topLeft.InitWithTexture(_scale9Image.Texture, lefttopbounds);
                _scale9Image.AddChild(_topLeft, 2, (int)Positions.TopLeft);

                // Top right
                _topRight = new CCSprite();
                _topRight.InitWithTexture(_scale9Image.Texture, righttopbounds);
                _scale9Image.AddChild(_topRight, 2, (int)Positions.TopRight);

                // Bottom left
                _bottomLeft = new CCSprite();
                _bottomLeft.InitWithTexture(_scale9Image.Texture, leftbottombounds);
                _scale9Image.AddChild(_bottomLeft, 2, (int)Positions.BottomLeft);

                // Bottom right
                _bottomRight = new CCSprite();
                _bottomRight.InitWithTexture(_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();
                _centre.InitWithTexture(_scale9Image.Texture, rotatedcenterbounds, true);
                _scale9Image.AddChild(_centre, 0, (int)Positions.Centre);

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

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

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

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

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

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

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

                // Bottom right
                _bottomRight = new CCSprite();
                _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);
        }
Ejemplo n.º 29
0
 public CCLabelTTF (string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment) :
     this (text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top)
 { }
Ejemplo n.º 30
0
        /**
         * Returns an autoreleased scroll view object.
         *
         * @param size view size
         * @param container parent object
         * @return autoreleased scroll view object
         */

        public CCScrollView(CCSize size, CCNode container)
        {
            InitWithViewSize(size, container);
        }
Ejemplo n.º 31
0
        public void CreateFontChars()
        {
            int nextFontPositionX = 0;
            int nextFontPositionY = 0;
            //unsigned short prev = -1;
            int kerningAmount = 0;

            CCSize tmpSize = CCSize.Zero;

            int longestLine = 0;
            int totalHeight = 0;

            int quantityOfLines = 1;

            int stringLen = m_sString.Length;

            if (stringLen == 0)
            {
                return;
            }

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

            totalHeight       = m_pConfiguration.m_nCommonHeight * quantityOfLines;
            nextFontPositionY = 0 - (m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);

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

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

                // unichar is a short, and an int is needed on HASH_FIND_INT
                CCBMFontConfiguration.ccBMFontDef fontDef = m_pConfiguration.m_pFontDefDictionary[c];

                CCRect rect = fontDef.rect;
                rect = CCMacros.CCRectanglePixelsToPoints(rect);

                rect.Origin.X += m_tImageOffset.X;
                rect.Origin.Y += m_tImageOffset.Y;

                CCSprite fontChar;

                fontChar = (CCSprite)(GetChildByTag(i));
                if (fontChar == null)
                {
                    fontChar = new CCSprite(m_pobTextureAtlas.Texture, rect);
                    AddChild(fontChar, 0, i);
                }
                else
                {
                    // reusing fonts
                    fontChar.SetTextureRect(rect, false, rect.Size);

                    // restore to default in case they were modified
                    fontChar.Visible = true;
                    fontChar.Opacity = 255;
                }

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
                var fontPos = new CCPoint((float)nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
                                          (float)nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
                fontChar.Position = CCMacros.CCPointPixelsToPoints(fontPos);

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

                // Apply label properties
                fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;
                // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
                fontChar.Color = m_tColor;

                // only apply opacity if it is different than 255 )
                // to prevent modifying the color too (issue #610)
                if (m_cOpacity != 255)
                {
                    fontChar.Opacity = m_cOpacity;
                }

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

            tmpSize.Width  = longestLine;
            tmpSize.Height = totalHeight;

            ContentSize = CCMacros.CCSizePixelsToPoints(tmpSize);
        }
Ejemplo n.º 32
0
 public static CCSize CCSizePointsToPixels(CCSize size)
 {
     return(size);
 }
Ejemplo n.º 33
0
        public FontTest()
        {
            CCSize s = CCDirector.SharedDirector.WinSize;
            CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, backCallback);
            CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, restartCallback);
            CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, nextCallback);

            CCMenu menu = new CCMenu(item1, item2, item3);
            menu.Position = CCPoint.Zero;
            item1.Position = new CCPoint(s.Width / 2 - item2.ContentSize.Width * 2, item2.ContentSize.Height / 2);
            item2.Position = new CCPoint(s.Width / 2, item2.ContentSize.Height / 2);
            item3.Position = new CCPoint(s.Width / 2 + item2.ContentSize.Width * 2, item2.ContentSize.Height / 2);
            AddChild(menu, 1);

            var blockSize = new CCSize(s.Width / 3, 200);

            CCLayerColor leftColor = new CCLayerColor(new CCColor4B(100, 100, 100, 255), blockSize.Width,
                                                      blockSize.Height);
            CCLayerColor centerColor = new CCLayerColor(new CCColor4B(200, 100, 100, 255), blockSize.Width,
                                                        blockSize.Height);
            CCLayerColor rightColor = new CCLayerColor(new CCColor4B(100, 100, 200, 255), blockSize.Width,
                                                       blockSize.Height);

            leftColor.IgnoreAnchorPointForPosition = false;
            centerColor.IgnoreAnchorPointForPosition = false;
            rightColor.IgnoreAnchorPointForPosition = false;

            leftColor.AnchorPoint = new CCPoint(0, 0.5f);
            centerColor.AnchorPoint = new CCPoint(0, 0.5f);
            rightColor.AnchorPoint = new CCPoint(0, 0.5f);

            leftColor.Position = new CCPoint(0, s.Height / 2);
            ;
            centerColor.Position = new CCPoint(blockSize.Width, s.Height / 2);
            rightColor.Position = new CCPoint(blockSize.Width * 2, s.Height / 2);

            AddChild(leftColor, -1);
            AddChild(rightColor, -1);
            AddChild(centerColor, -1);

            showFont(FontTestScene.restartAction());
        }
Ejemplo n.º 34
0
 public bool InitWithString(string label, string fontName, float fontSize, CCSize dimensions, CCTextAlignment alignment)
 {
     return(InitWithString(label, fontName, fontSize, dimensions, alignment, CCVerticalTextAlignment.Top));
 }
Ejemplo n.º 35
0
 /**
  * An intialized table view object
  *
  * @param dataSource data source
  * @param size view size
  * @return table view
  */
 public CCTableView(ICCTableViewDataSource dataSource, CCSize size)
     : this(dataSource, size, null)
 {
 }
Ejemplo n.º 36
0
 internal static CCSize MeasureString(string textg, CTFont font, CCSize layoutArea)
 {
     return(MeasureString(textg, font, new CCRect(0, 0, layoutArea.Width, layoutArea.Height)));
 }
Ejemplo n.º 37
0
        public void AddSpriteFramesWithDictionary(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(pobTexture,
                                                    new CCRect(x, y, w, h),
                                                    false,
                                                    new CCPoint(ox, oy),
                                                    new CCSize(ow, oh)
                                                    );
                }
                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(pobTexture,
                                                    frame,
                                                    rotated,
                                                    offset,
                                                    sourceSize
                                                    );
                }
                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 (m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            if (m_pSpriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }
                        if (!m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            m_pSpriteFramesAliases.Add(oneAlias, frameKey);
                        }
                    }

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

                // add sprite frame
                string key = pair.Key;
                if (!_AllowFrameOverwrite && m_pSpriteFrames.ContainsKey(key))
                {
                    CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
                }
                else if (_AllowFrameOverwrite || !m_pSpriteFrames.ContainsKey(key))
                {
                    m_pSpriteFrames[key] = spriteFrame;
                }
            }
        }
Ejemplo n.º 38
0
 public static bool Equal(ref CCSize size1, ref CCSize size2)
 {
     return((size1.Width == size2.Width) && (size1.Height == size2.Height));
 }
Ejemplo n.º 39
0
        private 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

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


                    _spriteFrames [name] = spriteFrame;
                }
            }
        }
Ejemplo n.º 40
0
 public bool Equals(CCSize s)
 {
     return(Width == s.Width && Height == s.Height);
 }
Ejemplo n.º 41
0
        public void AlignItemsVerticallyWithPadding(float padding)
        {
            float width = 0f;
            float height = -padding;

            if (m_pChildren != null && m_pChildren.count > 0)
            {
                for (int i = 0, count = m_pChildren.count; i < count; i++)
                {
                    CCNode pChild = m_pChildren[i];
                    if (!pChild.Visible)
                    {
                        continue;
                    }
                    height += pChild.ContentSize.Height * pChild.ScaleY + padding;
                    width = Math.Max(width, pChild.ContentSize.Width * pChild.ScaleX);
                }
            }

            float y = height / 2.0f;

            if (m_pChildren != null && m_pChildren.count > 0)
            {
                for (int i = 0, count = m_pChildren.count; i < count; i++)
                {
                    CCNode pChild = m_pChildren[i];
                    if (!pChild.Visible)
                    {
                        continue;
                    }
                    pChild.Position = new CCPoint(0, y - pChild.ContentSize.Height * pChild.ScaleY / 2.0f);
                    y -= pChild.ContentSize.Height * pChild.ScaleY + padding;
                    width = Math.Max(width, pChild.ContentSize.Width * pChild.ScaleX);
                }
            }
            ContentSize = new CCSize(width, height);
        }
Ejemplo n.º 42
0
        public virtual bool Init()
        {
            SetDefaultValues();

            // scenes
            m_pRunningScene = null;
            m_pNextScene    = null;

            m_pNotificationNode = null;

            m_dOldAnimationInterval = m_dAnimationInterval = 1.0 / kDefaultFPS;

            // Set default projection (3D)
            m_eProjection = CCDirectorProjection.Default;

            // projection delegate if "Custom" projection is used
            m_pProjectionDelegate = null;

            // FPS
            m_fAccumDt         = 0.0f;
            m_pFPSLabel        = null;
            m_pUpdateTimeLabel = null;
            m_pDrawTimeLabel   = null;
            m_pDrawsLabel      = null;
            m_bDisplayStats    = false;
            m_uTotalFrames     = 0;

            m_pStopwatch = new Stopwatch();

            // paused ?
            m_bPaused = false;

            // purge ?
            m_bPurgeDirecotorInNextLoop = false;

            m_obWinSizeInPoints = CCSize.Zero;

            //m_pobOpenGLView = null;

            m_fContentScaleFactor = 1.0f;

            // scheduler
            m_pScheduler = new CCScheduler();
            // action manager
            m_pActionManager = new CCActionManager();
            m_pScheduler.ScheduleUpdateForTarget(m_pActionManager, CCScheduler.kCCPrioritySystem, false);
            // touchDispatcher
            m_pTouchDispatcher = new CCTouchDispatcher();
            m_pTouchDispatcher.Init();

            // KeypadDispatcher
            m_pKeypadDispatcher = new CCKeypadDispatcher();

            // KeyboardDispatcher
            m_pKeyboardDispatcher = new CCKeyboardDispatcher();

            // Accelerometer
#if !PSM && !NETFX_CORE
            m_pAccelerometer = new CCAccelerometer();
#endif
            // create autorelease pool
            //CCPoolManager::sharedPoolManager()->push();

            m_NeedsInit = false;
            return(true);
        }
Ejemplo n.º 43
0
        public CCNode ReadNodeGraphFromFile(string fileName, object owner, CCSize parentSize)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return null;
            }

            string strCCBFileName = fileName;
            string strSuffix = ".ccbi";
            // Add ccbi suffix
            if (!CCBReader.EndsWith(strCCBFileName, strSuffix))
            {
                strCCBFileName += strSuffix;
            }

            string strPath = CCFileUtils.FullPathFromRelativePath(strCCBFileName);

            var pBytes = CCFileUtils.GetFileBytes(strPath);
            byte[] data = pBytes;

            CCNode ret = ReadNodeGraphFromData(data, owner, parentSize);

            return ret;
        }
Ejemplo n.º 44
0
 public override void Draw()
 {
     CCSize s = CCDirector.SharedDirector.WinSize;
     //ccDrawLine(new CCPoint(0, s.height / 2), new CCPoint(s.width, s.height / 2));
     //ccDrawLine(new CCPoint(s.width / 2, 0), new CCPoint(s.width / 2, s.height));
 }
Ejemplo n.º 45
0
        public CCScene CreateSceneWithNodeGraphFromFile(string fileName, object owner, CCSize parentSize)
        {
            CCNode pNode = ReadNodeGraphFromFile(fileName, owner, parentSize);
            CCScene pScene = new CCScene();
            pScene.AddChild(pNode);

            return pScene;
        }
Ejemplo n.º 46
0
        public bool InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment,
                                   CCVerticalTextAlignment vAlignment, string fontName,
                                   float fontSize)
        {
            try
            {
                Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);

                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }

                float loadedSize = fontSize;

                SpriteFont font = CCSpriteFontCache.SharedInstance.TryLoadFont(fontName, fontSize, out loadedSize);

                if (font == null)
                {
                    CCLog.Log("Failed to load default font. No font supported.");
                    return(false);
                }

                float scale = 1f;

                if (loadedSize != 0)
                {
                    scale = fontSize / loadedSize;
                }

                if (dimensions.Equals(CCSize.Zero))
                {
                    Vector2 temp = font.MeasureString(text);
                    dimensions.Width  = temp.X * scale;
                    dimensions.Height = temp.Y * scale;
                }

                var textList = new List <String>();
                var nextText = new StringBuilder();

                string[] lineList = text.Split('\n');

                float spaceWidth = font.MeasureString(" ").X *scale;

                for (int j = 0; j < lineList.Length; ++j)
                {
                    string[] wordList = lineList[j].Split(' ');

                    float lineWidth = 0;
                    bool  firstWord = true;

                    for (int i = 0; i < wordList.Length; ++i)
                    {
                        float wordWidth = font.MeasureString(wordList[i]).X *scale;

                        if ((lineWidth + wordWidth) > dimensions.Width)
                        {
                            lineWidth = wordWidth;

                            if (nextText.Length > 0)
                            {
                                firstWord = true;
                                textList.Add(nextText.ToString());
#if XBOX || XBOX360
                                nextText.Length = 0;
#else
                                nextText.Clear();
#endif
                            }
                            else
                            {
                                lineWidth += wordWidth;
                                firstWord  = false;
                                textList.Add(wordList[i]);
                                continue;
                            }
                        }
                        else
                        {
                            lineWidth += wordWidth;
                        }
                        if (!firstWord)
                        {
                            nextText.Append(' ');
                            lineWidth += spaceWidth;
                        }

                        nextText.Append(wordList[i]);
                        firstWord = false;
                    }

                    textList.Add(nextText.ToString());
#if XBOX || XBOX360
                    nextText.Length = 0;
#else
                    nextText.Clear();
#endif
                }

                if (dimensions.Height == 0)
                {
                    dimensions.Height = textList.Count * font.LineSpacing * scale;
                }

                //*  for render to texture
                RenderTarget2D renderTarget = CCDrawManager.CreateRenderTarget(
                    (int)dimensions.Width, (int)dimensions.Height,
                    DefaultAlphaPixelFormat, RenderTargetUsage.DiscardContents
                    );

                CCDrawManager.SetRenderTarget(renderTarget);
                CCDrawManager.Clear(Color.Transparent);

                SpriteBatch sb = CCDrawManager.spriteBatch;
                sb.Begin();

                float textHeight = textList.Count * font.LineSpacing * scale;
                float nextY      = 0;

                if (vAlignment == CCVerticalTextAlignment.Bottom)
                {
                    nextY = dimensions.Height - textHeight;
                }
                else if (vAlignment == CCVerticalTextAlignment.Center)
                {
                    nextY = (dimensions.Height - textHeight) / 2.0f;
                }

                for (int j = 0; j < textList.Count; ++j)
                {
                    string line = textList[j];

                    var position = new Vector2(0, nextY);

                    if (hAlignment == CCTextAlignment.Right)
                    {
                        position.X = dimensions.Width - font.MeasureString(line).X *scale;
                    }
                    else if (hAlignment == CCTextAlignment.Center)
                    {
                        position.X = (dimensions.Width - font.MeasureString(line).X *scale) / 2.0f;
                    }

                    sb.DrawString(font, line, position, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);

                    nextY += font.LineSpacing * scale;
                }

                sb.End();

                CCDrawManager.graphicsDevice.RasterizerState   = RasterizerState.CullNone;
                CCDrawManager.graphicsDevice.DepthStencilState = DepthStencilState.Default;

                CCDrawManager.SetRenderTarget((RenderTarget2D)null);

                if (InitWithTexture(renderTarget, renderTarget.Format, true, false))
                {
                    m_CacheInfo.CacheType = CCTextureCacheType.String;
                    m_CacheInfo.Data      = new CCStringCache()
                    {
                        Dimensions = dimensions,
                        Text       = text,
                        FontName   = fontName,
                        FontSize   = fontSize,
                        HAlignment = hAlignment,
                        VAlignment = vAlignment
                    };

                    return(true);
                }
            }
            catch (Exception ex)
            {
                CCLog.Log(ex.ToString());
            }
            return(false);
        }
Ejemplo n.º 47
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(m_sString))
            {
                return;
            }

            int stringLen = m_sString.Length;

            var charSet = m_pConfiguration.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 (m_sString[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            totalHeight = m_pConfiguration.m_nCommonHeight * quantityOfLines;
            nextFontPositionY = 0 -
                                (m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);

            CCBMFontConfiguration.CCBMFontDef fontDef = null;
            CCRect rect;

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

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

                if (charSet.IndexOf(c) == -1)
                {
                    CCLog.Log("Cocos2D.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 (!m_pConfiguration.m_pFontDefDictionary.TryGetValue(c, out fontDef))
                {
                    CCLog.Log("cocos2d::CCLabelBMFont: characer not found {0}", (int) c);
                    continue;
                }

                rect = fontDef.rect;
                rect = CCMacros.CCRectanglePixelsToPoints(rect);

                rect.Origin.X += m_tImageOffset.X;
                rect.Origin.Y += m_tImageOffset.Y;

                CCSprite fontChar;

                //bool hasSprite = true;
                fontChar = (CCSprite) (GetChildByTag(i));
                if (fontChar != null)
                {
                    // Reusing previous Sprite
                    fontChar.Visible = true;
                }
                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();
                        fontChar.InitWithTexture(m_pobTextureAtlas.Texture, rect);
                        AddChild(fontChar, i, i);
                    }

                    // Apply label properties
                    fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;

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

                // updating previous sprite
                fontChar.SetTextureRect(rect, false, rect.Size);

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
                var fontPos =
                    new CCPoint(
                        (float) nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
                        (float) nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
                fontChar.Position = CCMacros.CCPointPixelsToPoints(fontPos);

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

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

                //if (! hasSprite)
                //{
                //  UpdateQuadFromSprite(fontChar, i);
                //}
            }

            // 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.xAdvance < fontDef.rect.Size.Width)
            {
                tmpSize.Width = longestLine + fontDef.rect.Size.Width - fontDef.xAdvance;
            }
            else
            {
                tmpSize.Width = longestLine;
            }
            tmpSize.Height = totalHeight;

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

            ContentSize = CCMacros.CCSizePixelsToPoints(tmpSize);
        }
Ejemplo n.º 48
0
        public virtual bool Init()
        {
            SetDefaultValues();

            // scenes
            m_pRunningScene = null;
            m_pNextScene = null;

            m_pNotificationNode = null;

            m_dOldAnimationInterval = m_dAnimationInterval = 1.0 / kDefaultFPS;

            // Set default projection (3D)
            m_eProjection = CCDirectorProjection.Default;

            // projection delegate if "Custom" projection is used
            m_pProjectionDelegate = null;

            // FPS
            m_fAccumDt = 0.0f;
            m_pFPSLabel = null;
            m_pUpdateTimeLabel = null;
            m_pDrawTimeLabel = null;
            m_pDrawsLabel = null;
            m_bDisplayStats = false;
            m_uTotalFrames = 0;

            m_pStopwatch = new Stopwatch();

            // paused ?
            m_bPaused = false;

            // purge ?
            m_bPurgeDirecotorInNextLoop = false;

            m_obWinSizeInPoints = CCSize.Zero;

            //m_pobOpenGLView = null;

            m_fContentScaleFactor = 1.0f;

            // scheduler
            m_pScheduler = new CCScheduler();
            // action manager
            m_pActionManager = new CCActionManager();
            m_pScheduler.ScheduleUpdateForTarget(m_pActionManager, CCScheduler.kCCPrioritySystem, false);
            // touchDispatcher
            m_pTouchDispatcher = new CCTouchDispatcher();
            m_pTouchDispatcher.Init();

            // KeypadDispatcher
            m_pKeypadDispatcher = new CCKeypadDispatcher();

			// KeyboardDispatcher
			m_pKeyboardDispatcher = new CCKeyboardDispatcher();

			// Accelerometer
#if !PSM &&!NETFX_CORE
            m_pAccelerometer = new CCAccelerometer();
#endif
            // create autorelease pool
            //CCPoolManager::sharedPoolManager()->push();

            m_NeedsInit = false;
            return true;
        }
Ejemplo n.º 49
0
        public bool InitWithString(string text, string fontName, float fontSize,
                                   CCSize dimensions, CCTextAlignment hAlignment,
                                   CCVerticalTextAlignment vAlignment)
        {
            if (base.Init())
            {
                // shader program
                //this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM));

                m_tDimensions = new CCSize(dimensions.Width, dimensions.Height);
                m_hAlignment = hAlignment;
                m_vAlignment = vAlignment;
                m_pFontName = fontName;
                m_fFontSize = fontSize;

                Label = (text);

                return true;
            }

            return false;
        }
Ejemplo n.º 50
0
 public CCScrollView(CCSize size)
 {
     InitWithViewSize(size, null);
 }
Ejemplo n.º 51
0
 public CCLabelTTF (string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment,
                    CCVerticalTextAlignment vAlignment)
 {
     InitWithString(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
 }
Ejemplo n.º 52
0
        public static CCSize PointsToPixels(this CCSize s)
        {
            var cs = CCDirector.SharedDirector.ContentScaleFactor;

            return(new CCSize(s.Width * cs, s.Height * cs));
        }
Ejemplo n.º 53
0
 public CCLabel(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment)
 {
     InitWithString(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
 }
Ejemplo n.º 54
0
 public bool InitWithString(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment)
 {
     return(InitWithString(text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top));
 }
Ejemplo n.º 55
0
        public void showFont(string pFont)
        {
            CCSize s = CCDirector.SharedDirector.WinSize;

            var blockSize = new CCSize(s.Width / 3, 200);
            float fontSize = 26;

            RemoveChildByTag(kTagLabel1, true);
            RemoveChildByTag(kTagLabel2, true);
            RemoveChildByTag(kTagLabel3, true);
            RemoveChildByTag(kTagLabel4, true);

            CCLabelTTF top = new CCLabelTTF(pFont, "Arial", 24);
            CCLabelTTF left = new CCLabelTTF("alignment left", pFont, fontSize,
                                             blockSize, CCTextAlignment.Left,
                                             FontTestScene.verticalAlignment[FontTestScene.vAlignIdx]);
            CCLabelTTF center = new CCLabelTTF("alignment center", pFont, fontSize,
                                               blockSize, CCTextAlignment.Center,
                                               FontTestScene.verticalAlignment[FontTestScene.vAlignIdx]);
            CCLabelTTF right = new CCLabelTTF("alignment right", pFont, fontSize,
                                              blockSize, CCTextAlignment.Right,
                                              FontTestScene.verticalAlignment[FontTestScene.vAlignIdx]);

            top.AnchorPoint = new CCPoint(0.5f, 1);
            left.AnchorPoint = new CCPoint(0, 0.5f);
            center.AnchorPoint = new CCPoint(0, 0.5f);
            right.AnchorPoint = new CCPoint(0, 0.5f);

            top.Position = new CCPoint(s.Width / 2, s.Height - 20);
            left.Position = new CCPoint(0, s.Height / 2);
            center.Position = new CCPoint(blockSize.Width, s.Height / 2);
            right.Position = new CCPoint(blockSize.Width * 2, s.Height / 2);

            AddChild(left, 0, kTagLabel1);
            AddChild(right, 0, kTagLabel2);
            AddChild(center, 0, kTagLabel3);
            AddChild(top, 0, kTagLabel4);
        }
Ejemplo n.º 56
0
 public CCLabel(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment) :
     this(text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top)
 {
 }
Ejemplo n.º 57
0
        public override void UpdateTransform()
        {
            Debug.Assert(m_pobBatchNode != null,
                         "updateTransform is only valid when CCSprite is being rendered using an CCSpriteBatchNode");

            // recaculate matrix only if it is dirty
            if (Dirty)
            {
                // If it is not visible, or one of its ancestors is not visible, then do nothing:
                if (!m_bVisible ||
                    (m_pParent != null && m_pParent != m_pobBatchNode && ((CCSprite)m_pParent).m_bShouldBeHidden))
                {
                    m_sQuad.BottomRight.Vertices =
                        m_sQuad.TopLeft.Vertices = m_sQuad.TopRight.Vertices = m_sQuad.BottomLeft.Vertices = new CCVertex3F(0, 0, 0);
                    m_bShouldBeHidden            = true;
                }
                else
                {
                    m_bShouldBeHidden = false;

                    if (m_pParent == null || m_pParent == m_pobBatchNode)
                    {
                        m_transformToBatch = NodeToParentTransform();
                    }
                    else
                    {
                        Debug.Assert((m_pParent as CCSprite) != null,
                                     "Logic error in CCSprite. Parent must be a CCSprite");
                        m_transformToBatch = CCAffineTransform.Concat(NodeToParentTransform(),
                                                                      ((CCSprite)m_pParent).
                                                                      m_transformToBatch);
                    }

                    //
                    // calculate the Quad based on the Affine Matrix
                    //

                    CCSize size = m_obRect.Size;

                    float x1 = m_obOffsetPosition.X;
                    float y1 = m_obOffsetPosition.Y;

                    float x2 = x1 + size.Width;
                    float y2 = y1 + size.Height;
                    float x  = m_transformToBatch.tx;
                    float y  = m_transformToBatch.ty;

                    float cr  = m_transformToBatch.a;
                    float sr  = m_transformToBatch.b;
                    float cr2 = m_transformToBatch.d;
                    float sr2 = -m_transformToBatch.c;
                    float ax  = x1 * cr - y1 * sr2 + x;
                    float ay  = x1 * sr + y1 * cr2 + y;

                    float bx = x2 * cr - y1 * sr2 + x;
                    float by = x2 * sr + y1 * cr2 + y;

                    float cx = x2 * cr - y2 * sr2 + x;
                    float cy = x2 * sr + y2 * cr2 + y;

                    float dx = x1 * cr - y2 * sr2 + x;
                    float dy = x1 * sr + y2 * cr2 + y;

                    m_sQuad.BottomLeft.Vertices  = new CCVertex3F(ax, ay, m_fVertexZ);
                    m_sQuad.BottomRight.Vertices = new CCVertex3F(bx, by, m_fVertexZ);
                    m_sQuad.TopLeft.Vertices     = new CCVertex3F(dx, dy, m_fVertexZ);
                    m_sQuad.TopRight.Vertices    = new CCVertex3F(cx, cy, m_fVertexZ);
                }

                m_pobTextureAtlas.UpdateQuad(ref m_sQuad, m_uAtlasIndex);
                m_bRecursiveDirty = false;
                m_bDirty          = false;
            }

            // recursively iterate over children
            if (m_bHasChildren)
            {
                CCNode[] elements = m_pChildren.Elements;
                if (m_pobBatchNode != null)
                {
                    for (int i = 0, count = m_pChildren.count; i < count; i++)
                    {
                        ((CCSprite)elements[i]).UpdateTransform();
                    }
                }
                else
                {
                    for (int i = 0, count = m_pChildren.count; i < count; i++)
                    {
                        var sprite = elements[i] as CCSprite;
                        if (sprite != null)
                        {
                            sprite.UpdateTransform();
                        }
                    }
                }
            }
        }
Ejemplo n.º 58
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 = (ICCLabelProtocol)_titleLabel;

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

            var rgbaLabel = (ICCRGBAProtocol)_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 (_doesAdjustBackgroundImage)
            {
                // 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)
                {
                    CCSize preferredSize = _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;
            }
        }
Ejemplo n.º 59
0
        public void SetOpenGlView()
        {
            // set size
            m_obWinSizeInPoints = CCDrawManager.DesignResolutionSize;

            CreateStatsLabel();

            SetGlDefaultValues();

            CCApplication.SharedApplication.TouchDelegate = m_pTouchDispatcher;
            m_pTouchDispatcher.IsDispatchEvents = true;
        }
Ejemplo n.º 60
0
        public static CCSize CCSizePixelsToPoints(CCSize size)
        {
            var cs = CCDirector.SharedDirector.ContentScaleFactor;

            return(new CCSize(size.Width / cs, size.Height / cs));
        }