private Typeface TrySetFont(string fontName) { try { return(Typeface.CreateFromAsset(Context.Assets, "fonts/" + fontName)); } catch (Exception ex) { Console.WriteLine("not found in assets. Exception: {0}", ex); try { return(Typeface.CreateFromFile("fonts/" + fontName)); } catch (Exception ex1) { Console.WriteLine("not found by file. Exception: {0}", ex1); return(Typeface.Default); } } }
public static Typeface LoadTypefaceFromRaw(Context context, int resource) { Typeface tf = null; Stream inputStream = context.Resources.OpenRawResource(resource); string path = context.FilesDir + "/judo_fonts"; if (!Directory.Exists(path)) { try { Directory.CreateDirectory(path); } catch (Exception) { return(null); } } string outPath = path + "/courier.ttf"; if (File.Exists(outPath)) { tf = Typeface.CreateFromFile(outPath); } else { try { byte[] buffer = new byte[inputStream.Length]; BufferedStream bufferedStream = new BufferedStream(File.Open(outPath, FileMode.CreateNew)); int length = 0; while ((length = inputStream.Read(buffer, 0, buffer.Length)) > 0) { bufferedStream.Write(buffer, 0, length); } bufferedStream.Close(); tf = Typeface.CreateFromFile(outPath); } catch (Exception) { return(null); } } return(tf); }
private Tuple <Typeface, TypefaceStyle?> GetTypefaceFromAttrs(Typeface typeface, string fontFamily, string styleName) { if (fontFamily != null) { Typeface normalTypeface = null; if (fontFamily.Contains(".ttf") || fontFamily.Contains(".otf")) { // should be a custom font to try to get from font assets or file // try to get from assets try { normalTypeface = Typeface.CreateFromAsset(Context.Assets, fontFamily); } catch { // try to get from files try { normalTypeface = Typeface.CreateFromFile(fontFamily); } catch { throw new Exception("Neither Font Asset nor Font File found at " + fontFamily); } } } else { // should be a system font or a font-family xml resource normalTypeface = Typeface.Create(fontFamily, TypefaceStyle.Normal); } // if typeface found if (normalTypeface != null) { return(ResolveStyleAndSetTypeface(normalTypeface, styleName)); } } return(ResolveStyleAndSetTypeface(typeface, styleName)); }
private Typeface TrySetFont(string fontName) { try { return(Typeface.CreateFromAsset(Forms.Context.Assets, "fonts/" + fontName)); } catch (Exception ex) { Shared.Services.Logs.Insights.Send("TrySetFont", ex); Console.WriteLine("not found in assets. Exception: {0}", ex); try { return(Typeface.CreateFromFile("fonts/" + fontName)); } catch (Exception ex1) { Console.WriteLine("not found by file. Exception: {0}", ex1); return(Typeface.Default); } } }
/// <summary> /// Load the FA font from assets /// </summary> /// <param name="fontName"></param> /// <returns></returns> private Typeface TrySetFont(string fontName) { try { var tp = Typeface.CreateFromAsset(Context.Assets, "fonts/" + fontName); return(tp); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("not found in assets. Exception: {0}", ex)); try { return(Typeface.CreateFromFile("fonts/" + fontName)); } catch (Exception ex1) { System.Diagnostics.Debug.WriteLine(string.Format("not found by file. Exception: {0}", ex1)); return(Typeface.Default); } } }
/// <summary> /// Tries the set font. /// </summary> /// <param name="fontName">Name of the font.</param> /// <returns>Typeface.</returns> private Typeface TrySetFont(string fontName) { Typeface tf = Typeface.Default; try { return(FontCache.GetTypeFace(fontName)); } catch (Exception ex) { Console.Write("not found in assets {0}", ex); try { tf = Typeface.CreateFromFile(fontName); return(tf); } catch (Exception ex1) { Console.Write(ex1); return(Typeface.Default); } } }
static Typeface LoadAndRegisterEmbeddedFont(string resouceId, Assembly assembly) { using (var inputStream = EmbeddedResourceCache.GetStream(resouceId, assembly)) { if (inputStream == null) { System.Console.WriteLine("Embedded Resource for FontFamily \"" + resouceId + "\" not found."); return(null); } var cachedFontDir = new File(CustomFontDirRoot + "/ResourceFonts"); if (!cachedFontDir.Exists()) { cachedFontDir.Mkdir(); } var cachedFontFile = new File(cachedFontDir, resouceId); using (var outputStream = new FileOutputStream(cachedFontFile)) { const int bufferSize = 1024; var buffer = new byte[bufferSize]; int length = -1; while ((length = inputStream.Read(buffer, 0, bufferSize)) > 0) { outputStream.Write(buffer, 0, length); } } Typeface typeface = Typeface.CreateFromFile(cachedFontFile); if (typeface == null) { System.Console.WriteLine("Embedded Resource font file (" + resouceId + ") could not be loaded as an Android Typeface."); return(null); } _fontFiles.Add(resouceId, cachedFontFile.AbsolutePath); return(typeface); } }
/// <summary> /// Tries the set font. /// </summary> /// <param name="fontName">Name of the font.</param> /// <returns>Typeface.</returns> private Typeface TrySetFont(string fontName) { var typeface = Typeface.Default; try { typeface = Typeface.CreateFromAsset(_context.Assets, fontName); } catch (Exception ex) { Console.WriteLine("not found in assets {0}", ex); try { typeface = Typeface.CreateFromFile(fontName); } catch (Exception ex1) { Console.WriteLine(ex1); } } return(typeface); }
public static Typeface ToExtendedTypeface(this string fontFamily, double fontSize, string namedSize, int fontAttributes, Context context) { Typeface typeface = null; var hashKey = ToHasmapKeyWithFontFamily(fontFamily, fontSize, namedSize, fontAttributes); typeface = TypefaceCache.SharedCache.RetrieveTypeface(hashKey); if (typeface == null && !string.IsNullOrEmpty(fontFamily)) { string filename = fontFamily; if (filename.LastIndexOf(".", System.StringComparison.Ordinal) != filename.Length - 4) { filename = string.Format("{0}.ttf", filename); } try { var path = "fonts/" + filename; typeface = Typeface.CreateFromAsset(context.Assets, path); } catch { try { typeface = Typeface.CreateFromFile("fonts/" + filename); } catch { } } } if (typeface == null) { typeface = Typeface.Default; } TypefaceCache.SharedCache.StoreTypeface(hashKey, typeface); return(typeface); }
/// <summary> /// This method returns typeface for given typeface using following rules: /// 1. Lookup in the cache /// 2. If not found, look in the assets in the fonts folder. Save your font under its FontFamily name. /// If no extension is written in the family name .ttf is asumed /// 3. If not found look in the files under fonts/ folder /// If no extension is written in the family name .ttf is asumed /// 4. If not found, try to return typeface from Xamarin.Forms ToTypeface() method /// 5. If not successfull, return Typeface.Default /// </summary> /// <returns>The extended typeface.</returns> /// <param name="font">Font</param> /// <param name="context">Android Context</param> public static Typeface ToExtendedTypeface(this Font font, Context context) { Typeface typeface = null; //1. Lookup in the cache var hashKey = font.ToHasmapKey(); typeface = TypefaceCache.SharedCache.RetrieveTypeface(hashKey); #if DEBUG if (typeface != null) { Console.WriteLine("Typeface for font {0} found in cache", font); } #endif //2. If not found, try custom asset folder if (typeface == null && !string.IsNullOrEmpty(font.FontFamily)) { string filename = font.FontFamily; //if no extension given then assume and add .ttf if (filename.LastIndexOf(".", System.StringComparison.Ordinal) != filename.Length - 4) { filename = string.Format("{0}.ttf", filename); } try { var path = "fonts/" + filename; #if DEBUG Console.WriteLine("Lookking for font file: {0}", path); #endif typeface = Typeface.CreateFromAsset(context.Assets, path); #if DEBUG Console.WriteLine("Found in assets and cached."); #endif } catch (Exception ex) { #if DEBUG Console.WriteLine("not found in assets. Exception: {0}", ex); Console.WriteLine("Trying creation from file"); #endif try { typeface = Typeface.CreateFromFile("fonts/" + filename); #if DEBUG Console.WriteLine("Found in file and cached."); #endif } catch (Exception ex1) { #if DEBUG Console.WriteLine("not found by file. Exception: {0}", ex1); Console.WriteLine("Trying creation using Xamarin.Forms implementation"); #endif } } } //3. If not found, fall back to default Xamarin.Forms implementation to load system font if (typeface == null) { typeface = font.ToTypeface(); } if (typeface == null) { #if DEBUG Console.WriteLine("Falling back to default typeface"); #endif typeface = Typeface.Default; } //Store in cache TypefaceCache.SharedCache.StoreTypeface(hashKey, typeface); return(typeface); }
public static Typeface TypefaceForFontFamily(string fontFamily, Assembly assembly = null) { //string fontFilePath; if (fontFamily == null) { //return Typeface.Default; return(null); } Typeface result; if (fontFamily.ToLower() == "monospace") { result = TrySystemFont("monospace"); if (result != null) { return(result); } result = TrySystemFont("Droid Sans Mono"); if (result != null) { return(result); } } if (fontFamily.ToLower() == "serif") { result = TrySystemFont("serif"); if (result != null) { return(result); } result = TrySystemFont("Droid Serif"); if (result != null) { return(result); } } if (fontFamily.ToLower() == "sans-serif") { result = TrySystemFont("sans-serif"); if (result != null) { return(result); } result = TrySystemFont("normal"); if (result != null) { return(result); } result = TrySystemFont("Roboto"); if (result != null) { return(result); } result = TrySystemFont("Droid Sans"); if (result != null) { return(result); } } result = TrySystemFont(fontFamily); if (result != null) { return(result); } if (fontFamily.Contains(".Resources.Fonts.")) { // it's an Embedded Resource if (!fontFamily.ToLower().EndsWith(".ttf") && !fontFamily.ToLower().EndsWith(".otf")) { throw new InvalidObjectException("Embedded Font file names must end with \".ttf\" or \".otf\"."); } // what is the assembly? /* * var assemblyName = fontFamily.Substring(0, fontFamily.IndexOf(".Resources.Fonts.")); * * //var assembly = System.Reflection.Assembly.Load (assemblyName); * var assembly = ReflectionExtensions.GetAssemblyByName(assemblyName) ?? Forms9Patch.Droid.Settings.ApplicationAssembly; * * if (assembly == null) * { * // try using the current application assembly instead (as is the case with Shared Applications) * assembly = ReflectionExtensions.GetAssemblyByName(assemblyName + ".Droid"); * ///System.Console.WriteLine ("Assembly for FontFamily \"" + fontFamily + "\" not found."); * //return null; * } */ // move it to the Application's CustomFontDirRoot using (var inputStream = EmbeddedResourceCache.GetStream(fontFamily, assembly)) { if (inputStream == null) { System.Console.WriteLine("Embedded Resource for FontFamily \"" + fontFamily + "\" not found."); return(null); } var cachedFontDir = new File(CustomFontDirRoot + "/ResourceFonts"); if (!cachedFontDir.Exists()) { cachedFontDir.Mkdir(); } var cachedFontFile = new File(cachedFontDir, fontFamily); using (var outputStream = new FileOutputStream(cachedFontFile)) { const int bufferSize = 1024; var buffer = new byte[bufferSize]; int length = -1; while ((length = inputStream.Read(buffer, 0, bufferSize)) > 0) { outputStream.Write(buffer, 0, length); } } Typeface typeface = Typeface.CreateFromFile(cachedFontFile); if (typeface == null) { System.Console.WriteLine("Embedded Resource font file (" + fontFamily + ") could not be loaded as an Android Typeface."); return(null); } _fontFiles.Add(fontFamily, cachedFontFile.AbsolutePath); return(typeface); } } return(null); }
public Typeface GetTypeface(string name) { if (name == null || SystemFont.Equals(name)) { return(Typeface.Default); } if (SystemBoldFont.Equals(name)) { return(Typeface.DefaultBold); } if (GetFontStyleById(name) is NativeFontStyle fontStyle) { if (!_typeFaces.TryGetValue(name, out var typeface)) { string path; if (fontStyle.Resource) { var resource = fontStyle.Path; var resourceParts = resource.Split('.'); var fileName = $"{resourceParts[resourceParts.Length - 2]}.{resourceParts[resourceParts.Length - 1]}"; path = System.IO.Path.Combine(UserFontsPath, fileName); if (!File.Exists(path)) { if (!Directory.Exists(UserFontsPath)) { Directory.CreateDirectory(UserFontsPath); } var assembly = typeof(NativeFontService).Assembly; using (var stream = assembly.GetManifestResourceStream(resource)) { using (var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { stream?.CopyTo(outputStream); } } } } else { path = fontStyle.Path; } try { typeface = Typeface.CreateFromFile(path); if (typeface != null) { _typeFaces[name] = typeface; } } catch (Java.Lang.RuntimeException exc) { Logger.Info("Unable to load font from the file: " + fontStyle.Path, exc); } catch (Exception exc) { Logger.Info("Unable to load font from the file: " + fontStyle.Path, exc); } } if (typeface != null) { return(typeface); } } return(Typeface.Default); }