public (bool success, string filePath) LoadFont(EmbeddedFont font)
 {
     try
     {
         var data     = NSData.FromStream(font.ResourceStream);
         var provider = new CGDataProvider(data);
         var cGFont   = CGFont.CreateFromProvider(provider);
         var name     = cGFont.PostScriptName;
         if (CTFontManager.RegisterGraphicsFont(cGFont, out var error))
         {
             return(true, name);
         }
         else                 //Lets check if the font is already registered
         {
             var uiFont = NSFont.FromFontName(name, 10);
             if (uiFont != null)
             {
                 return(true, name);
             }
         }
         Debug.WriteLine(error.Description);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
     }
     return(false, null);
 }
Exemple #2
0
        internal static void loadFontIfNeeded(string fontName)
        {
            string loadedFont;

            MaterialFontLoader.LoadedFonts.TryGetValue(fontName, out loadedFont);
            if ((loadedFont == null) && (UIFont.FromName(name: fontName, size: 1) == null))
            {
                MaterialFontLoader.LoadedFonts[fontName] = fontName;
                var bundle     = NSBundle.FromClass(new Class(typeof(MaterialFontLoader)));
                var identifier = bundle.BundleIdentifier;
                var fontURL    = bundle.GetUrlForResource(name: fontName, fileExtension: "ttf", subdirectory: "Fonts/Roboto");
                if (fontURL != null)
                {
                    var data     = NSData.FromUrl(fontURL);
                    var provider = new CGDataProvider(data);
                    var font     = CGFont.CreateFromProvider(provider);

                    NSError error;
                    if (!CoreText.CTFontManager.RegisterGraphicsFont(font, out error))
                    {
                        var errerrorDescription = error.Description;
                        throw new Exception(error.Description);
                        //new NSException(name: NSException.con, reason: error.Description, userInfo: error.UserInfo);
                    }
                }
            }
        }
 static UIFont LoadAndRegisterEmbeddedFont(string resourceId, nfloat size, Assembly assembly)
 {
     using (var stream = EmbeddedResourceCache.GetStream(resourceId, assembly))
     {
         if (stream == null)
         {
             Console.WriteLine("Could not open Embedded Resource [" + resourceId + "]");
             return(null);
         }
         var data = NSData.FromStream(stream);
         if (data == null)
         {
             Console.WriteLine("Could not retrieve data from Embedded Resource [" + resourceId + "].");
             return(null);
         }
         var provider = new CGDataProvider(data);
         var font     = CGFont.CreateFromProvider(provider);
         if (!CTFontManager.RegisterGraphicsFont(font, out NSError error))
         {
             if (error.Code != 105)
             {
                 Console.WriteLine("Could load but failed to register [" + resourceId + "] font.  Error messages:");
                 Console.WriteLine("\tdescription: " + error.Description);
                 throw new MissingMemberException("Failed to register [" + resourceId + "] font.  Error messages in console.");
             }
         }
         _embeddedResourceFonts.Add(resourceId, font.PostScriptName);
         return(UIFont.FromName(font.PostScriptName, size));
     }
 }
        public IFont LoadFontFromPath(string path, float sizeInPoints, FontStyle style = FontStyle.Regular)
        {
            CGFont cgFont = _installedFonts.GetOrAdd(path, _ =>
            {
                try
                {
                    CGFont createdFont = CGFont.CreateFromProvider(new CGDataProvider(path));
                    NSError error;
                    if (!CTFontManager.RegisterGraphicsFont(createdFont, out error))
                    {
                        Debug.WriteLine($"Failed to load font from {path} (loading default font instead), error: {error.ToString()}");
                        return(null);
                    }
                    return(createdFont);
                }
                catch (ArgumentException e)
                {
                    Debug.WriteLine($"Failed to load font from {path} (loading default font instead), exception: {e.ToString()}");
                    return(null);
                }
            });

            if (cgFont == null)
            {
                return(LoadFont("Helvetica", sizeInPoints, style));
            }

            CTFont font = new CTFont(cgFont, sizeInPoints, CGAffineTransform.MakeIdentity());

            font = setFontStyle(font, sizeInPoints, style);
            return(new IOSFont(font, style, this));
        }
Exemple #5
0
        private static UIFont GetFontFromFile(nfloat size, string file)
        {
            var fileName      = Path.GetFileNameWithoutExtension(file);
            var fileExtension = Path.GetExtension(file)?.Replace(".", "");

            var url = NSBundle
                      .MainBundle
                      .GetUrlForResource(
                name: fileName,
                fileExtension: fileExtension,
                subdirectory: "Fonts"
                );

            if (url == null)
            {
                return(null);
            }

            var fontData = NSData.FromUrl(url);

            if (fontData == null)
            {
                return(null);
            }

            //iOS loads UIFonts based on the PostScriptName of the font file
            using (var fontProvider = new CGDataProvider(fontData))
            {
                using (var font = CGFont.CreateFromProvider(fontProvider))
                {
                    return(font != null?UIFont.FromName(font.PostScriptName, size) : null);
                }
            }
        }
Exemple #6
0
        //We need to register fonts with iOS runtime
        //Take a look at following article for more details
        //https://marco.org/2012/12/21/ios-dynamic-font-loading
        protected override async Task InstallFonts(IEnumerable <CustomFont> fonts)
        {
            NSError error = null;

            foreach (var font in fonts)
            {
                //If font data is null we need to load it from a font file
                if (font.Data == null)
                {
                    var fontFile = await FontFolder.GetFileAsync(font.File);

                    using (var stream = await fontFile.OpenAsync(FileAccess.Read))
                    {
                        font.Data = new byte[stream.Length];
                        await stream.ReadAsync(font.Data, 0, font.Data.Length);
                    }
                }
                var fontData = NSData.FromArray(font.Data);
                using (CGDataProvider provider = new CGDataProvider(fontData))
                {
                    using (CGFont nativeFont = CGFont.CreateFromProvider(provider))
                    {
                        CTFontManager.RegisterGraphicsFont(nativeFont, out error);
                        if (error != null)
                        {
                            Console.WriteLine(error);
                        }
                    }
                }
            }
        }
        public (bool success, string?filePath) LoadFont(EmbeddedFont font)
        {
            try
            {
                if (font.ResourceStream == null)
                {
                    throw new InvalidOperationException("ResourceStream was null.");
                }

                var data     = NSData.FromStream(font.ResourceStream);
                var provider = new CGDataProvider(data);
                var cGFont   = CGFont.CreateFromProvider(provider);
                var name     = cGFont.PostScriptName;

                if (CTFontManager.RegisterGraphicsFont(cGFont, out var error))
                {
                    return(true, name);
                }

                var uiFont = UIFont.FromName(name, 10);
                if (uiFont != null)
                {
                    return(true, name);
                }

                throw new NSErrorException(error);
            }
            catch (Exception ex)
            {
                _logger?.LogWarning(ex, "Unable register font {Font} with the system.", font.FontName);
            }

            return(false, null);
        }
        private static CGFont _CreateLatinMathCg()
        {
            var manifestProvider = IosResourceProviders.Manifest();

            byte[] buffer = manifestProvider.ManifestContents(LatinMathFontName + ".otf");
            using (CGDataProvider fontDataProvider = new CGDataProvider(buffer))
            {
                var r = CGFont.CreateFromProvider(fontDataProvider);
                return(r);
            }
        }
        public string?LoadFont(EmbeddedFont font)
        {
            try
            {
                CGFont?cgFont;

                if (font.ResourceStream == null)
                {
                    if (!System.IO.File.Exists(font.FontName))
                    {
                        throw new InvalidOperationException("ResourceStream was null.");
                    }

                    var provider = new CGDataProvider(font.FontName);
                    cgFont = CGFont.CreateFromProvider(provider);
                }
                else
                {
                    var data = NSData.FromStream(font.ResourceStream);
                    if (data == null)
                    {
                        throw new InvalidOperationException("Unable to load font stream data.");
                    }
                    var provider = new CGDataProvider(data);
                    cgFont = CGFont.CreateFromProvider(provider);
                }

                if (cgFont == null)
                {
                    throw new InvalidOperationException("Unable to load font from the stream.");
                }

                var name = cgFont.PostScriptName;

                if (CTFontManager.RegisterGraphicsFont(cgFont, out var error))
                {
                    return(name);
                }

                var uiFont = UIFont.FromName(name, 10);
                if (uiFont != null)
                {
                    return(name);
                }

                throw new NSErrorException(error);
            }
            catch (Exception ex)
            {
                _serviceProvider?.CreateLogger <EmbeddedFontLoader>()?.LogWarning(ex, "Unable register font {Font} with the system.", font.FontName);
            }

            return(null);
        }
 static AppleMathFont()
 {
     using var fontDataProvider = new CGDataProvider(
               Foundation.NSData.FromStream(
                   new Resources.ManifestResourceProvider(
                       System.Reflection.Assembly.GetExecutingAssembly()
                       ).ManifestStream(LatinMathFontName + ".otf")
                   )
               );
     LatinMathCG = CGFont.CreateFromProvider(fontDataProvider);
 }
Exemple #11
0
        public static void LoadFont(string name, string format)
        {
            var bundle  = NSBundle.FromClass(new Class(typeof(NBMaterialCircularActivityIndicator)));
            var fontURL = bundle.GetUrlForResource(name, format);
            var data    = NSData.FromUrl(fontURL);

            var provider = new CGDataProvider(data);
            var font     = CGFont.CreateFromProvider(provider);

            NSError error;

            if (!CTFontManager.RegisterGraphicsFont(font, out error))
            {
                throw new NSErrorException(error);
            }
        }
Exemple #12
0
        public IFont LoadFontFromPath(string path, float sizeInPoints, FontStyle style = FontStyle.Regular)
        {
            CGFont cgFont = _installedFonts.GetOrAdd(path, _ =>
            {
                CGFont createdFont = CGFont.CreateFromProvider(new CGDataProvider(path));
                NSError error;
                if (!CTFontManager.RegisterGraphicsFont(createdFont, out error))
                {
                    Debug.WriteLine("Failed to load font from {0} (loading default font instead), error: {1}", path, error.ToString());
                    return null;
                }
                return createdFont;
            });
            if (cgFont == null) return LoadFont("Helvetica", sizeInPoints, style);

            CTFont font = new CTFont(cgFont, sizeInPoints, CGAffineTransform.MakeIdentity());
            font = setFontStyle(font, sizeInPoints, style);
            return new IOSFont(font, style);
        }
Exemple #13
0
        public (bool success, string filePath) LoadFont(EmbeddedFont font)
        {
            try
            {
                var data = NSData.FromStream(font.ResourceStream);

                var provider = new CGDataProvider(data);
                var cGFont   = CGFont.CreateFromProvider(provider);
                if (CTFontManager.RegisterGraphicsFont(cGFont, out var error))
                {
                    return(true, null);
                }
                Debug.WriteLine(error.Description);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            return(false, null);
        }
        static void LoadFontFrom(string path)
        {
            try
            {
                CGDataProvider provider = new CGDataProvider(path);
                CGFont         font     = CGFont.CreateFromProvider(provider);

                if (font.NumberOfGlyphs > 0)
                {
#if USE_WEAKREFERENCE
                    cachedFont = new WeakHandle <CGFont> (font);
#else
                    cachedFont = font;
#endif
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to load font : " + ex);
                throw ex;
            }
        }
        /// <summary>
        /// Init this instance to
        /// </summary>
        public static void Init()
        {
            NControl.Controls.FontLoader.LoadFonts(AppDomain.CurrentDomain.GetAssemblies(), (fontName, s) => {
                var data = new byte[s.Length];
                s.Read(data, 0, data.Length);

                var dataProvider = new CGDataProvider(data, 0, data.Length);
                var cgFont       = CGFont.CreateFromProvider(dataProvider);
                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: " + fontName +
                                                    " (" + error.LocalizedDescription + ")");
                    }
                }
            });
        }
        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);
                }
            }
        }
        internal static UIFont EmbeddedFont(string resourceId, nfloat size, Assembly assembly = null)
        {
            if (resourceId == "STIXGeneral")
            {
                resourceId = "Forms9Patch.Resources.Fonts.STIXGeneral.otf";
            }

            if (_embeddedResourceFonts.ContainsKey(resourceId))
            {
                string family = _embeddedResourceFonts[resourceId];
                return(UIFont.FromName(family, size));
            }
            if (resourceId.Contains(".Resources.Fonts."))
            {
                // it's an Embedded Resource
                if (!resourceId.ToLower().EndsWith(".ttf") && !resourceId.ToLower().EndsWith(".otf"))
                {
                    throw new MissingMemberException("Embedded Font file names must end with \".ttf\" or \".otf\".");
                }
                lock (_loadFontLock)
                {
                    // what is the assembly?

                    /*
                     * var assemblyName = resourceId.Substring(0, resourceId.IndexOf(".Resources.Fonts."));
                     * //var assembly = System.Reflection.Assembly.Load (assemblyName);
                     * var assembly = ReflectionExtensions.GetAssemblyByName(assemblyName);
                     * if (assembly == null)
                     * {
                     *  // try using the current application assembly instead (as is the case with Shared Applications)
                     *  assembly = ReflectionExtensions.GetAssemblyByName(assemblyName + ".Droid");
                     *  //Console.WriteLine ("Assembly for Resource ID \"" + resourceID + "\" not found.");
                     *  //return null;
                     * }
                     */
                    // load it!
                    using (var stream = EmbeddedResourceCache.GetStream(resourceId, assembly))
                    {
                        if (stream == null)
                        {
                            Console.WriteLine("Could not open Embedded Resource [" + resourceId + "]");
                            return(null);
                        }
                        var data = NSData.FromStream(stream);
                        if (data == null)
                        {
                            Console.WriteLine("Could not retrieve data from Embedded Resource [" + resourceId + "].");
                            return(null);
                        }
                        var provider = new CGDataProvider(data);
                        var font     = CGFont.CreateFromProvider(provider);
                        if (!CTFontManager.RegisterGraphicsFont(font, out NSError error))
                        {
                            if (error.Code != 105)
                            {
                                Console.WriteLine("Could load but failed to register [" + resourceId + "] font.  Error messages:");
                                Console.WriteLine("\tdescription: " + error.Description);
                                throw new MissingMemberException("Failed to register [" + resourceId + "] font.  Error messages in console.");
                            }
                        }
                        _embeddedResourceFonts.Add(resourceId, font.PostScriptName);
                        return(UIFont.FromName(font.PostScriptName, size));
                    }
                }
            }
            return(null);
        }
Exemple #18
0
 public void CreateFromProvider()
 {
     Assert.Null(CGFont.CreateFromProvider(null), "CreateFromProvider");
 }
Exemple #19
0
        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 dataProvider = GetFontDataProvider(fileName);
                    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);
        }
Exemple #20
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;

            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);
        }