List<string> NativeFontFamilies()
        {
            if (nativeFontCollection == null)
            {
                var collectionOptions = new CTFontCollectionOptions ();
                collectionOptions.RemoveDuplicates = true;
                nativeFontCollection = new CTFontCollection (collectionOptions);
                nativeFontDescriptors = new Dictionary<string, CTFontDescriptor> ();
            }

            var fontdescs = nativeFontCollection.GetMatchingFontDescriptors ();

            foreach (var fontdesc in fontdescs)
            {
                var font = new CTFont (fontdesc, 0);

                // Just in case RemoveDuplicates collection option is not working
                if (!nativeFontDescriptors.ContainsKey (font.FamilyName))
                {
                    nativeFontDescriptors.Add (font.FamilyName, fontdesc);
                }

            }
            var fontFamilies = new List<string> (nativeFontDescriptors.Keys);

            return fontFamilies;
        }
Esempio n. 2
0
		public CTGlyphInfo (string glyphName, CTFont font, string baseString)
		{
			if (glyphName == null)
				throw ConstructorError.ArgumentNull (this, "glyphName");
			if (font == null)
				throw ConstructorError.ArgumentNull (this, "font");
			if (baseString == null)
				throw ConstructorError.ArgumentNull (this, "baseString");

			using (var gn = new NSString (glyphName))
			using (var bs = new NSString (baseString))
				Handle = CTGlyphInfoCreateWithGlyphName (gn.Handle, font.Handle, bs.Handle);

			if (Handle == IntPtr.Zero)
				throw ConstructorError.Unknown (this);
		}
		private void CreateFont(string fontName, float fontSize, CCRawList<char> charset)
		{

			_font = CCLabelUtilities.CreateFont (fontName, fontSize);

			var value = new CCLabelUtilities.ABCFloat[1];

			_abcValues.Clear();;

			for (int i = 0; i < charset.Count; i++)
			{
				var ch = charset[i];
				CCLabelUtilities.GetCharABCWidthsFloat(ch, _font, out value);
				_abcValues.Add(ch, new KerningInfo() { A = value[0].abcfA, B = value[0].abcfB, C = value[0].abcfC });
			}

		}
        private void CreateNativeFont(FontFamily familyName, float emSize, FontStyle style,
			GraphicsUnit unit, byte gdiCharSet, bool  gdiVerticalFont )
        {
            // convert to 96 Dpi to be consistent with Windows
            var dpiSize = emSize * dpiScale;

            try
            {
                nativeFont = new CTFont(familyName.NativeDescriptor,dpiSize);
            }
            catch
            {
                nativeFont = new CTFont("Helvetica",dpiSize);
            }

            CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

            if ((style & FontStyle.Bold) == FontStyle.Bold)
                tMask |= CTFontSymbolicTraits.Bold;
            if ((style & FontStyle.Italic) == FontStyle.Italic)
                tMask |= CTFontSymbolicTraits.Italic;
            strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout;
            underLine = (style & FontStyle.Underline) == FontStyle.Underline;

            var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize,tMask,tMask);

            if (nativeFont2 != null)
                nativeFont = nativeFont2;

            bold = (nativeFont.SymbolicTraits & CTFontSymbolicTraits.Bold) == CTFontSymbolicTraits.Bold;
            italic = (nativeFont.SymbolicTraits & CTFontSymbolicTraits.Italic) == CTFontSymbolicTraits.Italic;
            sizeInPoints = emSize;
            this.unit = unit;

            // FIXME
            // I do not like the hard coded 72 but am just trying to boot strap the Font class right now
            size = ConversionHelpers.GraphicsUnitConversion(GraphicsUnit.Point, unit, 72.0f, sizeInPoints);
        }
Esempio n. 5
0
 public void SetFont(CTFont font)
 {
     if (font == null)
         throw new ArgumentNullException ("font");
     _Font = font.Handle;
 }
		static internal CTFont CreateFont (string familyName, float emSize, FontStyle style,
		                        byte gdiCharSet, bool  gdiVerticalFont )
		{
			if (emSize <= 0)
				throw new ArgumentException("emSize is less than or equal to 0, evaluates to infinity, or is not a valid number.","emSize");

			CTFont nativeFont;
			// convert to 96 Dpi to be consistent with Windows
			var dpiSize = emSize * dpiScale;

			var ext = System.IO.Path.GetExtension(familyName);
			if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
			{
				var fontName = familyName.Substring (0, familyName.Length - ext.Length);
				var path = CCApplication.SharedApplication.Game.Content.RootDirectory + Path.DirectorySeparatorChar + fontName;
				var pathForResource = NSBundle.MainBundle.PathForResource (path, ext.Substring(1));

				try {
					var dataProvider = new CGDataProvider (pathForResource);
					var cgFont = CGFont.CreateFromProvider (dataProvider);

					try {
						nativeFont = new CTFont(cgFont, dpiSize, null);
					}
					catch
					{
						nativeFont = new CTFont("Helvetica",dpiSize);
					}
				}
				catch (Exception)
				{
					try {
						nativeFont = new CTFont(Path.GetFileNameWithoutExtension(familyName),dpiSize);
					}
					catch
					{
						nativeFont = new CTFont("Helvetica",dpiSize);
					}	
					CCLog.Log (string.Format ("Could not load font: {0} so will use default {1}.", familyName, nativeFont.DisplayName));

				}
			}
			else
			{
				try {
					nativeFont = new CTFont(familyName,dpiSize);
				}
				catch
				{
					nativeFont = new CTFont("Helvetica",dpiSize);
				}
			}


			CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

			if ((style & FontStyle.Bold) == FontStyle.Bold)
				tMask |= CTFontSymbolicTraits.Bold;
			if ((style & FontStyle.Italic) == FontStyle.Italic)
				tMask |= CTFontSymbolicTraits.Italic;
			strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout;
			underLine = (style & FontStyle.Underline) == FontStyle.Underline;

			var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize,tMask,tMask);

			if (nativeFont2 != null)
				nativeFont = nativeFont2;

			return nativeFont;
		}
		private static NSMutableAttributedString buildAttributedString(string text, CTFont font, 
		                                                               CCColor4B? fontColor=null) 
		{

			// Create a new attributed string definition
			var ctAttributes = new CTStringAttributes ();

			// Font attribute
			ctAttributes.Font = font;
			// -- end font 

			if (fontColor.HasValue) {

				// Font color
				var fc = fontColor.Value;
                var cgColor = new CGColor(fc.R / 255f, 
                                             fc.G / 255f,
                                             fc.B / 255f,
                                             fc.A / 255f);

				ctAttributes.ForegroundColor = cgColor;
				ctAttributes.ForegroundColorFromContext = false;
				// -- end font Color
			}

			if (underLine) {
				// Underline
				#if MACOS
				int single = (int)MonoMac.AppKit.NSUnderlineStyle.Single;
				int solid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid;
				var attss = single | solid;
				ctAttributes.UnderlineStyleValue = attss;
				#else
				ctAttributes.UnderlineStyleValue = 1;
				#endif
				// --- end underline
			}


			if (strikeThrough) {
				// StrikeThrough
				//				NSColor bcolor = NSColor.Blue;
				//				NSObject bcolorObject = new NSObject(bcolor.Handle);
				//				attsDic.Add(NSAttributedString.StrikethroughColorAttributeName, bcolorObject);
//				#if MACOS
//				int stsingle = (int)MonoMac.AppKit.NSUnderlineStyle.Single;
//				int stsolid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid;
//				var stattss = stsingle | stsolid;
//				var stunderlineObject = NSNumber.FromInt32(stattss);
//				#else
//				var stunderlineObject = NSNumber.FromInt32 (1);
//				#endif
//
//				attsDic.Add(StrikethroughStyleAttributeName, stunderlineObject);
				// --- end underline
			}


			// Text alignment
			var alignment = CTTextAlignment.Left;
			var alignmentSettings = new CTParagraphStyleSettings();
			alignmentSettings.Alignment = alignment;
			var paragraphStyle = new CTParagraphStyle(alignmentSettings);

			ctAttributes.ParagraphStyle = paragraphStyle;
			// end text alignment

            NSMutableAttributedString atts = 
                new NSMutableAttributedString(text,ctAttributes.Dictionary);

			return atts;

		}
Esempio n. 8
0
 internal void Dispose(bool disposing)
 {
     if (disposing){
         if (nativeFont != null){
             nativeFont.Dispose ();
             nativeFont = null;
         }
     }
 }
Esempio n. 9
0
		static internal CTFont CreateFont (string familyName, float emSize, FontStyle style,
		                                   byte gdiCharSet, bool  gdiVerticalFont )
		{
			if (emSize <= 0)
				throw new ArgumentException("emSize is less than or equal to 0, evaluates to infinity, or is not a valid number.","emSize");

			CTFont nativeFont;

			// convert to 96 Dpi to be consistent with Windows
			var dpiSize = emSize * dpiScale;

			try {
				nativeFont = new CTFont(familyName,dpiSize);
			}
			catch
			{
				nativeFont = new CTFont("Helvetica",dpiSize);
			}

			CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

			if ((style & FontStyle.Bold) == FontStyle.Bold)
				tMask |= CTFontSymbolicTraits.Bold;
			if ((style & FontStyle.Italic) == FontStyle.Italic)
				tMask |= CTFontSymbolicTraits.Italic;
			strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout;
			underLine = (style & FontStyle.Underline) == FontStyle.Underline;

			var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize,tMask,tMask);

			if (nativeFont2 != null)
				nativeFont = nativeFont2;

			return nativeFont;
		}
Esempio n. 10
0
		public CTGlyphInfo (CGGlyph glyph, CTFont font, string baseString)
		{
			if (font == null)
				throw ConstructorError.ArgumentNull (this, "font");
			if (baseString == null)
				throw ConstructorError.ArgumentNull (this, "baseString");

			using (var bs = new NSString (baseString))
				handle = CTGlyphInfoCreateWithGlyph (glyph, font.Handle, bs.Handle);

			if (handle == IntPtr.Zero)
				throw ConstructorError.Unknown (this);
		}
        private void CreateNativeFontFamily(string name, FontCollection fontCollection, bool createDefaultIfNotExists)
        {
            if (fontCollection != null)
            {
                if (fontCollection.nativeFontDescriptors.ContainsKey (name))
                    nativeFontDescriptor = fontCollection.nativeFontDescriptors [name];

                if (nativeFontDescriptor == null && createDefaultIfNotExists)
                {
                    nativeFontDescriptor = new CTFontDescriptor (SANS_SERIF, 0);
                }
            }
            else
            {
                nativeFontDescriptor = new CTFontDescriptor (name, 0);

                if (nativeFontDescriptor == null && createDefaultIfNotExists)
                {
                    nativeFontDescriptor = new CTFontDescriptor (SANS_SERIF, 0);
                }
            }

            if (nativeFontDescriptor == null)
                throw new ArgumentException ("name specifies a font that is not installed on the computer running the application.");
            else
            {
                var attrs = nativeFontDescriptor.GetAttributes ();
                familyName = attrs.FamilyName;
                // if the font description attributes do not contain a value for FamilyName then we
                // need to try and create the font to get the family name from the actual font.
                if (string.IsNullOrEmpty (familyName))
                {
                    var font = new CTFont (nativeFontDescriptor, 0);
                    familyName = font.FamilyName;
                }
            }
        }
		internal static void NativeDrawString (CGBitmapContext bitmapContext, string s, CTFont font, CCColor4B brush, CGRect layoutRectangle)
		{
			if (font == null)
				throw new ArgumentNullException ("font");

			if (s == null || s.Length == 0)
				return;

			bitmapContext.ConcatCTM (bitmapContext.GetCTM().Invert());

            // This is not needed here since the color is set in the attributed string.
			//bitmapContext.SetFillColor(brush.R/255f, brush.G/255f, brush.B/255f, brush.A/255f);

            // I think we only Fill the text with no Stroke surrounding
			//bitmapContext.SetTextDrawingMode(CGTextDrawingMode.Fill);

			var attributedString = buildAttributedString(s, font, brush);

			// Work out the geometry
			CGRect insetBounds = layoutRectangle;

			CGPoint textPosition = new CGPoint(insetBounds.X,
			                                 insetBounds.Y);

            float boundsWidth = (float)insetBounds.Width;

			// Calculate the lines
			nint start = 0;
            nint length = attributedString.Length;

			var typesetter = new CTTypesetter(attributedString);

			float baselineOffset = 0;

			// First we need to calculate the offset for Vertical Alignment if we 
			// are using anything but Top
			if (vertical != CCVerticalTextAlignment.Top) {
				while (start < length) {

                    nint count = typesetter.SuggestLineBreak((int)start, (double)boundsWidth);

                    var line = typesetter.GetLine (new NSRange(start, count));

					// Create and initialize some values from the bounds.
					nfloat ascent;
					nfloat descent;
					nfloat leading;
                    line.GetTypographicBounds(out ascent, out descent, out leading);
                    baselineOffset += (float)Math.Ceiling ((float)(ascent + descent + leading + 1)); // +1 matches best to CTFramesetter's behavior  
					line.Dispose ();
					start += count;
				}
			}

			start = 0;

			while (start < length && textPosition.Y < insetBounds.Bottom)
			{

				// Now we ask the typesetter to break off a line for us.
				// This also will take into account line feeds embedded in the text.
				//  Example: "This is text \n with a line feed embedded inside it"
                nint count = typesetter.SuggestLineBreak((int)start, (double)boundsWidth);
				var line = typesetter.GetLine(new NSRange(start, count));

				// Create and initialize some values from the bounds.
				nfloat ascent;
				nfloat descent;
				nfloat leading;
				line.GetTypographicBounds(out ascent, out descent, out leading);

				// Calculate the string format if need be
				var penFlushness = 0.0f;

				if (horizontal == CCTextAlignment.Right)
					penFlushness = (float)line.GetPenOffsetForFlush(1.0f, boundsWidth);
				else if (horizontal == CCTextAlignment.Center)
					penFlushness = (float)line.GetPenOffsetForFlush(0.5f, boundsWidth);

				// initialize our Text Matrix or we could get trash in here
				var textMatrix = CGAffineTransform.MakeIdentity();

				if (vertical == CCVerticalTextAlignment.Top)
					textMatrix.Translate(penFlushness, insetBounds.Height - textPosition.Y -(float)Math.Floor(ascent - 1));
				if (vertical == CCVerticalTextAlignment.Center)
					textMatrix.Translate(penFlushness, ((insetBounds.Height / 2) + (baselineOffset / 2)) - textPosition.Y -(float)Math.Floor(ascent - 1));
				if (vertical == CCVerticalTextAlignment.Bottom)
					textMatrix.Translate(penFlushness, baselineOffset - textPosition.Y -(float)Math.Floor(ascent - 1));

				// Set our matrix
				bitmapContext.TextMatrix = textMatrix;

				// and draw the line
				line.Draw(bitmapContext);

				// Move the index beyond the line break.
				start += count;
				textPosition.Y += (float)Math.Ceiling(ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior  
				line.Dispose();

			}

		}	
        /// <summary>
        /// Gets font metrics for the specified font.
        /// </summary>
        /// <param name="font">The font.</param>
        /// <param name="defaultLineHeight">Default line height.</param>
        /// <param name="delta">The vertical delta.</param>
        private void GetFontMetrics(CTFont font, out float defaultLineHeight, out float delta)
        {
            var ascent = font.AscentMetric;
            var descent = font.DescentMetric;
            var leading = font.LeadingMetric;

            //// http://stackoverflow.com/questions/5511830/how-does-line-spacing-work-in-core-text-and-why-is-it-different-from-nslayoutm

            leading = leading < 0 ? 0 : (float)Math.Floor (leading + 0.5f);
            var lineHeight = (float)Math.Floor (ascent + 0.5f) + (float)Math.Floor (descent + 0.5) + leading;
            var ascenderDelta = leading >= 0 ? 0 : (float)Math.Floor ((0.2 * lineHeight) + 0.5);
            defaultLineHeight = lineHeight + ascenderDelta;
            delta = ascenderDelta - descent;
        }
        void LoadFontFile(string fileName)
        {
            CTFont nativeFont;
            var dpiSize = 0;
            var ext = Path.GetExtension(fileName);

            if (!String.IsNullOrEmpty(ext))
            {

                if (nativeFontDescriptors == null)
                    nativeFontDescriptors = new Dictionary<string, CTFontDescriptor> ();

                //Try loading from Bundle first
                var fontName = fileName.Substring (0, fileName.Length - ext.Length);
                var pathForResource = NSBundle.MainBundle.PathForResource (fontName, ext.Substring(1));

                NSUrl url;

             				if (!string.IsNullOrEmpty(pathForResource))
                    url = NSUrl.FromFilename (pathForResource);
                else
                    url = NSUrl.FromFilename (fileName);

                // We will not use CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process);
                // here.  The reason is that there is no way we can be sure that the font can be created to
                // to identify the family name afterwards.  So instead we will create a CGFont from a data provider.
                // create CTFont to obtain the CTFontDescriptor, store family name and font descriptor to be accessed
                // later.
                try {
                    var dataProvider = new CGDataProvider (url.Path);
                    var cgFont = CGFont.CreateFromProvider (dataProvider);

                    try {
                        nativeFont = new CTFont(cgFont, dpiSize, null);
                        if (!nativeFontDescriptors.ContainsKey(nativeFont.FamilyName))
                        {
                            nativeFontDescriptors.Add(nativeFont.FamilyName, nativeFont.GetFontDescriptor());
                            NSError error;
                            var registered = CTFontManager.RegisterGraphicsFont(cgFont, out error);
                            if (!registered)
                            {
                                // If the error code is 105 then the font we are trying to register is already registered
                                // We will not report this as an error.
                                if (error.Code != 105)
                                    throw new ArgumentException("Error registering: " + Path.GetFileName(fileName));
                            }
                        }
                    }
                    catch
                    {
                        // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                        throw new System.IO.FileNotFoundException (fileName);
                    }
                }
                catch (Exception)
                {
                    // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                    throw new System.IO.FileNotFoundException (fileName);
                }
            }
        }
Esempio n. 15
0
        public Font(string familyName, float emSize, FontStyle style,
		             GraphicsUnit unit, byte gdiCharSet, bool  gdiVerticalFont )
        {
            if (emSize <= 0)
                throw new ArgumentException("emSize is less than or equal to 0, evaluates to infinity, or is not a valid number.","emSize");

            // convert to 96 Dpi to be consistent with Windows
            var dpiSize = emSize * dpiScale;

            try {
                nativeFont = new CTFont(familyName,dpiSize);
            }
            catch
            {
                //nativeFont = new CTFont("Lucida Grande",emSize);
                nativeFont = new CTFont("Helvetica",dpiSize);
            }

            CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

            if ((style & FontStyle.Bold) == FontStyle.Bold)
                tMask |= CTFontSymbolicTraits.Bold;
            if ((style & FontStyle.Italic) == FontStyle.Italic)
                tMask |= CTFontSymbolicTraits.Italic;
            strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout;
            underLine = (style & FontStyle.Underline) == FontStyle.Underline;

            var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize,tMask,tMask);

            if (nativeFont2 != null)
                nativeFont = nativeFont2;

            sizeInPoints = emSize;
            this.unit = unit;

            // FIXME
            // I do not like the hard coded 72 but am just trying to boot strap the Font class right now
            size = ConversionHelpers.GraphicsUnitConversion(GraphicsUnit.Point, unit, 72.0f, sizeInPoints);
        }
        private int GetNativeMetric(Metric metric, FontStyle style)
        {
            // we are going to actually have to create a font object here
            // will not create an actual variable for this yet.  We may
            // want to do this in the future so that we do not have to keep
            // creating it over and over again.
            CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

            if ((style & FontStyle.Bold) == FontStyle.Bold)
                tMask |= CTFontSymbolicTraits.Bold;
            if ((style & FontStyle.Italic) == FontStyle.Italic)
                tMask |= CTFontSymbolicTraits.Italic;

            var font = new CTFont (nativeFontDescriptor,0);
            font = font.WithSymbolicTraits (0, tMask, tMask);

            switch (metric)
            {
            case Metric.EMHeight:
                return (int)font.UnitsPerEmMetric;
            case Metric.CellAscent:
                return (int)Math.Round(font.AscentMetric / font.Size * font.UnitsPerEmMetric);
            case Metric.CellDescent:
                return (int)Math.Round(font.DescentMetric / font.Size * font.UnitsPerEmMetric);
            case  Metric.LineSpacing:
                float lineHeight = 0;
                lineHeight += font.AscentMetric;
                lineHeight += font.DescentMetric;
                lineHeight += font.LeadingMetric;
                return (int)Math.Round(lineHeight / font.Size * font.UnitsPerEmMetric);
            }

            return 0;
        }
        private bool NativeStyleAvailable(FontStyle style)
        {
            // we are going to actually have to create a font object here
            // will not create an actual variable for this yet.  We may
            // want to do this in the future so that we do not have to keep
            // creating it over and over again.
            var font = new CTFont (nativeFontDescriptor,0);

            switch (style)
            {
            case FontStyle.Bold:
                var tMaskBold = CTFontSymbolicTraits.None;
                tMaskBold |= CTFontSymbolicTraits.Bold;
                var bFont = font.WithSymbolicTraits (0, tMaskBold, tMaskBold);
                if (bFont == null)
                    return false;
                var bold = (bFont.SymbolicTraits & CTFontSymbolicTraits.Bold) == CTFontSymbolicTraits.Bold;
                return bold;

            case FontStyle.Italic:
                //return (font.SymbolicTraits & CTFontSymbolicTraits.Italic) == CTFontSymbolicTraits.Italic;
                var tMaskItalic = CTFontSymbolicTraits.None;
                tMaskItalic |= CTFontSymbolicTraits.Italic;
                var iFont = font.WithSymbolicTraits (0, tMaskItalic, tMaskItalic);
                if (iFont == null)
                    return false;
                var italic = (iFont.SymbolicTraits & CTFontSymbolicTraits.Italic) == CTFontSymbolicTraits.Italic;
                return italic;

            case FontStyle.Regular:

                // Verify if this is correct somehow - we may need to add Bold here as well not sure
                if ((font.SymbolicTraits & CTFontSymbolicTraits.Condensed) == CTFontSymbolicTraits.Condensed
                    ||  (font.SymbolicTraits & CTFontSymbolicTraits.Expanded) == CTFontSymbolicTraits.Expanded)
                    return false;
                else
                    return true;
            case FontStyle.Underline:
                return font.UnderlineThickness > 0;
            case FontStyle.Strikeout:
                // not implemented yet
                return false;

            }
            return false;
        }
		// This only handles one character for right now
		internal static void GetCharABCWidthsFloat (char characters, CTFont font, out ABCFloat[] abc)
		{

			var atts = buildAttributedString(characters.ToString(), font);

			// for now just a line not sure if this is going to work
			CTLine line = new CTLine(atts);

			nfloat ascent;
			nfloat descent;
			nfloat leading;
			abc = new ABCFloat[1];
			abc[0].abcfB = (float)line.GetTypographicBounds(out ascent, out descent, out leading);
            abc [0].abcfB += (float)leading;
		}
        void LoadFontAndGatherGlyphInfos(int unitSize, Action<List<GlyphInfo>> endHandler)
        {
            float scale = Window.BackingScaleFactor;
            Task.Factory.StartNew (() => {
                try {
                    Type typGlyphNames = typeof (FontAwesome.GlyphNames);
                    var memberinfos = typGlyphNames.GetMembers (BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty);

                    var ctFont = new CTFont (FontAwesomeUtil.Font, 20f, CGAffineTransform.MakeIdentity ());

                    var list = memberinfos.Select ((m) => {
                        var fieldInfo = typGlyphNames.GetField (m.Name);
                        var rawName = (string)fieldInfo.GetValue (typGlyphNames);
                        var glyphval = ctFont.GetGlyphWithName (rawName);
                        return new GlyphInfo {
                            GlyphName = m.Name
                                , RawName = rawName
                                    , GlyphImage = FontAwesomeUtil.GetImageForBarItem (rawName, unitSize, scale)
                                    , GlyphId = glyphval
                        };
                    }).ToList ();

                    if (endHandler != null)
                        endHandler (list);
                }
                catch (Exception ex) {
                    Console.WriteLine ("Exception: " + ex);
                }
            });
        }
		internal static CCSize MeasureString (string textg, CTFont font, CCRect rect)
		{

			var atts = buildAttributedString(textg, font);

			// for now just a line not sure if this is going to work
			CTLine line = new CTLine(atts);

			// Create and initialize some values from the bounds.
			nfloat ascent;
			nfloat descent;
			nfloat leading;
			double lineWidth = line.GetTypographicBounds(out ascent, out descent, out leading);

            var measure = new CCSize((float)(lineWidth + leading), (float)(ascent + descent));

			return measure;
		}
Esempio n. 21
0
		private static NSMutableAttributedString buildAttributedString(string text, CTFont font, 
		                                                               Color? fontColor=null) 
		{


			// Create a new attributed string from text
			NSMutableAttributedString atts = 
				new NSMutableAttributedString(text);

			var attRange = new NSRange(0, atts.Length);
			var attsDic = new NSMutableDictionary();

			// Font attribute
			NSObject fontObject = new NSObject(font.Handle);
			attsDic.Add(FontAttributedName, fontObject);
			// -- end font 

			if (fontColor.HasValue) {

				// Font color
				var fc = fontColor.Value;
				NSColor color = NSColor.FromDeviceRgba(fc.R / 255f, 
				                                       fc.G / 255f,
				                                       fc.B / 255f,
				                                       fc.A / 255f);
				NSObject colorObject = new NSObject(color.Handle);
				attsDic.Add(ForegroundColorAttributedName, colorObject);
				// -- end font Color
			}

			if (underLine) {
				// Underline
				int single = (int)MonoMac.AppKit.NSUnderlineStyle.Single;
				int solid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid;
				var attss = single | solid;
				var underlineObject = NSNumber.FromInt32(attss);
				//var under = NSAttributedString.UnderlineStyleAttributeName.ToString();
				attsDic.Add(UnderlineStyleAttributeName, underlineObject);
				// --- end underline
			}


			if (strikeThrough) {
				// StrikeThrough
				//				NSColor bcolor = NSColor.Blue;
				//				NSObject bcolorObject = new NSObject(bcolor.Handle);
				//				attsDic.Add(NSAttributedString.StrikethroughColorAttributeName, bcolorObject);
				int stsingle = (int)MonoMac.AppKit.NSUnderlineStyle.Single;
				int stsolid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid;
				var stattss = stsingle | stsolid;
				var stunderlineObject = NSNumber.FromInt32(stattss);

				attsDic.Add(StrikethroughStyleAttributeName, stunderlineObject);
				// --- end underline
			}


			// Text alignment
			var alignment = CTTextAlignment.Left;
			var alignmentSettings = new CTParagraphStyleSettings();
			alignmentSettings.Alignment = alignment;
			var paragraphStyle = new CTParagraphStyle(alignmentSettings);
			NSObject psObject = new NSObject(paragraphStyle.Handle);

			// end text alignment

			attsDic.Add(ParagraphStyleAttributeName, psObject);

			atts.SetAttributes(attsDic, attRange);

			return atts;

		}
		internal static CCSize MeasureString (string textg, CTFont font, CCSize layoutArea)
		{
			return MeasureString (textg, font, new CCRect (0, 0, layoutArea.Width, layoutArea.Height));
		}
		internal static CCSize MeasureString (string textg, CTFont font)
		{
			return MeasureString (textg, font, CCSize.Zero);
		}
        string LoadFontFile (string fileName)
        {
            CTFont nativeFont;
            var dpiSize = 0;
            var ext = Path.GetExtension(fileName);

            if (!String.IsNullOrEmpty(ext))
            {

                if (nativeFontDescriptors == null)
                    nativeFontDescriptors = new Dictionary<string, string> ();

                string fd = null;
                if (nativeFontDescriptors.TryGetValue(fileName, out fd))
                    return fd;
                        
                // We will not use CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process);
                // here.  The reason is that there is no way we can be sure that the font can be created to
                // to identify the family name afterwards.  So instead we will create a CGFont from a data provider.
                // create CTFont to obtain the CTFontDescriptor, store family name and font descriptor to be accessed
                // later.
                try {

                    var filePath = string.Empty;
                    CCContentManager.SharedContentManager.GetAssetStreamAsBytes(fileName, out filePath);

                    var dataProvider = new CGDataProvider (filePath);
                    var cgFont = CGFont.CreateFromProvider (dataProvider);

                    try 
                    {
                        nativeFont = new CTFont(cgFont, dpiSize, null);
                        if (!nativeFontDescriptors.ContainsKey(fileName))
                        {
                            nativeFontDescriptors.Add(fileName, nativeFont.PostScriptName);
                            NSError error;

                            var registered = CTFontManager.RegisterGraphicsFont(cgFont, out error);
                            if (!registered)
                            {
                                // If the error code is 105 then the font we are trying to register is already registered
                                // We will not report this as an error.
                                if (error.Code != 105)
                                    throw new ArgumentException("Error registering: " + Path.GetFileName(fileName));
                            }
                        }

                        return nativeFont.PostScriptName;
                    }
                    catch
                    {
                        // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                        throw new System.IO.FileNotFoundException (fileName);
                    }
                }
                catch (Exception)
                {
                    // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                    throw new System.IO.FileNotFoundException (fileName);

                }

            }
            return fileName;
        }