示例#1
0
        public string CreateStatusUpdatePoster(HpbStatistic hpbStatistic)
        {
            using (Image image = Image.Load(Configuration["HBP:LatestUpdateImage"]))
            {
                FontCollection fonts      = new FontCollection();
                FontFamily     fontFamily = fonts.Install(Configuration["HBP:font"]);

                String dateAndTime = hpbStatistic.LastUpdate.ToString("dd.MM.yyyy") + " - " + hpbStatistic.LastUpdate.ToString("hh.mm tt");

                image.Mutate(ctx => ctx.DrawText(dateAndTime, new Font(fontFamily, 60, FontStyle.Bold), Color.White, new PointF(50, 230)));

                image.Mutate(ctx => ctx.DrawText(hpbStatistic.LocalTotalCases.ToString(),
                                                 new Font(fontFamily, 80, FontStyle.Bold), Color.FromRgb(210, 9, 61), new PointF(40, 350)));

                image.Mutate(ctx => ctx.DrawText("New Cases : " + hpbStatistic.LocalNewCases.ToString(),
                                                 new Font(fontFamily, 25, FontStyle.Bold), Color.FromRgb(210, 9, 61), new PointF(30, 430)));

                image.Mutate(ctx => ctx.DrawText(hpbStatistic.LocalActiveCases.ToString(),
                                                 new Font(fontFamily, 80, FontStyle.Bold), Color.FromRgb(210, 9, 61), new PointF(40, 610)));

                image.Mutate(ctx => ctx.DrawText(hpbStatistic.LocalTotalNumberOfIndividualsInHospitals.ToString(),
                                                 new Font(fontFamily, 80, FontStyle.Bold), Color.FromRgb(210, 9, 61), new PointF(40, 850)));

                image.Mutate(ctx => ctx.DrawText(hpbStatistic.LocalRecoverd.ToString(),
                                                 new Font(fontFamily, 80, FontStyle.Bold), Color.ForestGreen, new PointF(40, 1110)));

                image.Mutate(ctx => ctx.DrawText(hpbStatistic.LocalDeaths.ToString(),
                                                 new Font(fontFamily, 90, FontStyle.Bold), Color.FromRgb(210, 9, 61), new PointF(80, 1355)));

                String imageName = "status_update_" + hpbStatistic.Id + ".jpg";

                image.Save(imageName);
                return(imageName);
            }
        }
示例#2
0
        public void MeasuringWordWithAccentedCharacterDoesNotThrow(char c)
        {
            FontFamily arial = new FontCollection().Add(TestFonts.OpenSansFile);
            var        font  = new Font(arial, 1f, FontStyle.Regular);

            FontRectangle size = TextMeasurer.Measure($"abc{c}def", new TextOptions(font));
        }
示例#3
0
        public static Stream GetImage(string astronaut1, string astronaut2, string messageContent, bool debugRectangle = false)
        {
            MemoryStream   stream = new MemoryStream();
            FontCollection fonts  = new FontCollection();

            fonts.Install(Path.Combine(assetsFolder, "fonts", "arial.ttf"));
            Font      captionFont             = fonts.CreateFont("arial", 8);
            Rectangle messageContentRectangle = new Rectangle(150, 50, 450, 165);
            Font      astronaut1Font          = fonts.CreateFont("arial", 7);
            Rectangle astronaut1Rectangle     = new Rectangle(350, 225, 150, 75);
            Font      astronaut2Font          = fonts.CreateFont("arial", 8);
            Rectangle astronaut2Rectangle     = new Rectangle(625, 50, 250, 125);
            Font      alwaysHasBeenFont       = fonts.CreateFont("arial", 9);
            Rectangle alwaysHasBeenRectangle  = new Rectangle(400, 0, 475, 50);

            using (Image img = Image.Load(Path.Combine(assetsFolder, "images", "wait-its-all-ohio.png")))
            {
                img.Mutate(ctx => ctx.DrawBoxedText(astronaut1Font, astronaut1, Color.White, Color.Black, astronaut1Rectangle, VerticalAlignment.Center, debugRectangle));
                img.Mutate(ctx => ctx.DrawBoxedText(astronaut2Font, astronaut2, Color.White, Color.Black, astronaut2Rectangle, VerticalAlignment.Center, debugRectangle));
                img.Mutate(ctx => ctx.DrawBoxedText(captionFont, messageContent, Color.White, Color.Black, messageContentRectangle, VerticalAlignment.Bottom, debugRectangle));
                img.Mutate(ctx => ctx.DrawBoxedText(alwaysHasBeenFont, "Always has been", Color.White, Color.Black, alwaysHasBeenRectangle, VerticalAlignment.Center, debugRectangle));
                img.SaveAsPng(stream);
            }
            stream.Position = 0;
            return(stream);
        }
示例#4
0
 public static IEnumerable <string> GetAllFontFamilyName()
 {
     using (Factory Fact = new Factory())
         using (FontCollection Collection = Fact.GetSystemFontCollection(new RawBool(false)))
         {
             for (int Index = 0; Index < Collection.FontFamilyCount; Index++)
             {
                 using (FontFamily Font = Collection.GetFontFamily(Index))
                 {
                     if (Font.FamilyNames.FindLocaleName(ApplicationLanguages.PrimaryLanguageOverride, out int NameStringIndex))
                     {
                         yield return(Font.FamilyNames.GetString(NameStringIndex));
                     }
                     else if (Font.FamilyNames.FindLocaleName("en-us", out int NameStringIndex1))
                     {
                         yield return(Font.FamilyNames.GetString(NameStringIndex1));
                     }
                     else
                     {
                         yield return(Font.FamilyNames.GetString(0));
                     }
                 }
             }
         }
 }
示例#5
0
        public LvFont() : base()
        {
            DoubleBuffered        = true;
            fc                    = new FontCollection();
            Sorting               = SortOrder.Ascending;
            this.OwnerDraw        = true;
            this.TileSize         = DefaultTileSize;
            this.ContextMenuStrip = new ContextMenuStrip();
            this.ContextMenuStrip.Items.AddRange(new ToolStripItem[] {
                new ToolStripFontItem("Detail", null, delegate { base.View = View.Details; }),
                new ToolStripFontItem("Tile", null, delegate { View = View.Tile; Invalidate(); }),
                new ToolStripFontItem("Icon", null, delegate { View = View.List; Invalidate(); }),
                new ToolStripFontItem("Large", null, delegate { View = View.LargeIcon; Invalidate(); }),
                new ToolStripFontItem("Small", null, delegate { View = View.SmallIcon; Invalidate(); }),
            });
            List <ListViewItem> lvitems = new List <ListViewItem>();

            foreach (FontFamily x in fc)
            {
                lvitems.Add(new ListViewItem(new string[] { x.Name, fc.ListStyles(x) }));
            }
            Items.AddRange(lvitems.ToArray());
            lvitems.Clear();
            lvitems = null;
        }
示例#6
0
        private async Task <List <string> > LoadCustomFontCharacters(string fontfamilyname, string fontFilePath)
        {
            var uri         = new Uri(fontFilePath);
            var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

            CurrentResourceFontLoader = new ResourceFontLoader(FactoryDWrite, await storageFile.OpenStreamForReadAsync());
            CurrentFontCollection     = new FontCollection(FactoryDWrite, CurrentResourceFontLoader,
                                                           CurrentResourceFontLoader.Key);

            var character = new List <string>();

            CurrentFontCollection.FindFamilyName(fontfamilyname, out var familyIndex);
            if (familyIndex == -1)
            {
                return(character);
            }

            using (var fontFamily = CurrentFontCollection.GetFontFamily(familyIndex))
            {
                var font  = fontFamily.GetFont(0);
                var count = 65536 * 4 - 1;
                for (var i = 0; i < count; i++)
                {
                    if (font.HasCharacter(i))
                    {
                        character.Add(char.ConvertFromUtf32(i));
                    }
                }
            }

            return(character);
        }
示例#7
0
        // Constructors.
        public FontFamily(GenericFontFamilies genericFamily)
        {
            this.genericFamily  = genericFamily;
            this.fontCollection = null;
            this.metricsStyle   = (FontStyle)(-1);
            switch (genericFamily)
            {
            case GenericFontFamilies.Serif:
            default:
            {
                this.name = "Times New Roman";
            }
            break;

            case GenericFontFamilies.SansSerif:
            {
                this.name = "Microsoft Sans Serif";
            }
            break;

            case GenericFontFamilies.Monospace:
            {
                this.name = "Courier New";
            }
            break;
            }
        }
示例#8
0
        /// <summary>
        /// Create class for generating captcha
        /// </summary>
        public GeneratedCaptcha()
        {
            FontFamily fontFamily = new FontCollection()
                                    .Install(Path.Combine(Directory.GetCurrentDirectory(), "LiberationSerif-Italic.ttf"));

            font = new Font(fontFamily, 48);
        }
示例#9
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }


            FontCollection fonts         = new FontCollection();
            var            actionManFont = fonts.Install("/home/peter/Pictures/captai/Action_Man.ttf");
            var            font          = new Font(actionManFont, 39, FontStyle.Regular);

            FontRectangle s = new FontRectangle(369, 80, 506, 302);

            var textGraphicOptions = new TextGraphicsOptions()
            {
                TextOptions =
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center,
                    WrapTextWidth       = 164.0f
                }
            };

            var result = "output.jpg";

            using (Image <Rgba32> image = (Image <Rgba32>)Image.Load("/home/peter/Pictures/captai/template.png"))
            {
                image.Mutate(x => x
                             .DrawText(textGraphicOptions, args[0], font, Color.Black, new PointF(362.0f, 171.0f))
                             );
                image.Save(result);
            }
        }
示例#10
0
        protected static Font CompileFontData(string a_fontFamily, float a_fontSize)
        {
            if (!string.IsNullOrEmpty(a_fontFamily))
            {
                FontFamily fontFamily = FontCollection.GetFontFamily(a_fontFamily);

                if (fontFamily != null)
                {
                    return(new Font(fontFamily, a_fontSize, GraphicsUnit.Pixel));
                }

                InstalledFontCollection fontCollection = new InstalledFontCollection();

                FontFamily[] fontFamilies = fontCollection.Families;

                foreach (FontFamily font in fontFamilies)
                {
                    if (font.Name == a_fontFamily)
                    {
                        return(new Font(font, a_fontSize, GraphicsUnit.Pixel));
                    }
                }
            }

            return(new Font(SystemFonts.DefaultFont.FontFamily, a_fontSize));
        }
示例#11
0
        private static List <string> GetFontNames()
        {
            List <string> fonts = new List <string>();

            using (DirectWriteFactory factory = DirectWriteFactory.Create(DirectWriteFactoryType.Shared))
            {
                using (FontCollection fontCollection = factory.GetSystemFontCollection(false))
                {
                    for (int index = 0; index < fontCollection.Count; ++index)
                    {
                        using (FontFamily fontFamily = fontCollection[index])
                        {
                            using (LocalizedStrings names = fontFamily.FamilyNames)
                            {
                                int cultureIndex = names.FindCulture(CultureInfo.CurrentUICulture);
                                if (cultureIndex < 0)
                                {
                                    cultureIndex = names.FindCulture(new CultureInfo("en-us"));
                                }
                                fonts.Add(names[cultureIndex]);
                            }
                        }
                    }
                }
            }
            fonts.Sort();
            return(fonts);
        }
示例#12
0
        public FontManager(IWebHostEnvironment env)
        {
            FontCollection collection = new FontCollection();
            var            fontFamily = collection.Install(env.GetFontPath("OpenSans-Bold.ttf"));

            DefaultFont = fontFamily.CreateFont(50.0f, FontStyle.Bold);
        }
示例#13
0
        private static Font GetFont(string fontName, float fontSize)
        {
            var fontFamily = GetFontFamily(fontName);

            if (fontFamily == null)
            {
                if (privateFontLoader == null)
                {
                    privateFontLoader     = new PrivateFontLoader(FactoryDWrite);
                    privateFontCollection = new FontCollection(FactoryDWrite, privateFontLoader, privateFontLoader.Key);
                }

                _currentFontCollection = privateFontCollection;
                fontFamily             = GetFontFamily(fontName);
            }

            if (fontFamily == null)
            {
                _currentFontCollection = FactoryDWrite.GetSystemFontCollection(true);
                return(GenericSanSerif());
            }

            // This is generic right now.  We should be able to handle different styles in the future
            var font = fontFamily.GetFirstMatchingFont(FontWeight.Regular, FontStretch.Normal, FontStyle.Normal);

            return(font);
        }
示例#14
0
        /// <summary>
        /// 初始化字体池
        /// </summary>
        /// <param name="fontSize">一个初始大小</param>
        private void initFonts(int fontSize)
        {
            if (_fontArr == null)
            {
                var assembly = Assembly.GetExecutingAssembly();
                var names    = assembly.GetManifestResourceNames();

                if (names?.Length > 0 == true)
                {
                    var fontList       = new List <Font>();
                    var fontCollection = new FontCollection();

                    foreach (var name in names)
                    {
                        fontList.Add(new Font(fontCollection.Install(assembly.GetManifestResourceStream(name)), fontSize));
                    }

                    _fontArr = fontList.ToArray();
                }
                else
                {
                    throw new Exception($"绘制验证码字体文件加载失败");
                }
            }
        }
示例#15
0
        public static Font CreateFont(string text)
        {
            FontCollection fc = new FontCollection();
            Font           d  = fc.Install(FakeFontInstance.CreateFontWithVaryingVerticalFontMetrics(text)).CreateFont(12);

            return(new Font(d, 1));
        }
示例#16
0
 public ControlWithMenu(EntityManager MathMLEntityManager, FontCollection FontCollection)
     : base(MathMLEntityManager, FontCollection)
 {
     this.designMode = false;
     this.InitializeComponent();
     this.CreateMenu();
 }
        private static Font CreateFont(string fontName, int size)
        {
            var    fontCollection = new FontCollection();
            string fontPath       = TestFontUtilities.GetPath(fontName);

            return(fontCollection.Install(fontPath).CreateFont(size));
        }
        public ScreenshotService()
        {
            var baseDir      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
            var resourcesDir = Path.Combine(baseDir, "Resources");

            _fontCollection = new FontCollection();
            _fontCollection.Install($"{resourcesDir}/OpenSans-Bold.ttf");
            _fontCollection.Install($"{resourcesDir}/OpenSans-Regular.ttf");
            _sun = Image.Load <Bgra32>($"{resourcesDir}/Sun.jpg");

            _unixJpegEncoder = _unixJpegEncoder = new JpegEncoder()
            {
                Quality = 50
            };
            _jpegEncoder = (source, stream) => source.Image.Save(stream, _unixJpegEncoder);
            if (OSInfo.IsWindows)
            {
                var winJpegEncoder = ImageCodecInfo
                                     .GetImageDecoders()
                                     .Single(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
                var winJpegEncoderParameters = new EncoderParameters(1)
                {
                    Param = new [] { new EncoderParameter(Encoder.Quality, 50L) }
                };
                _jpegEncoder = (source, stream) =>
                               source.Bitmap.Save(stream, winJpegEncoder, winJpegEncoderParameters);
            }
        }
示例#19
0
        public FontFamily(string name, FontCollection fontCollection)
        {
            IntPtr handle = (fontCollection == null) ? IntPtr.Zero : fontCollection.nativeFontCollection;
            Status status = GDIPlus.GdipCreateFontFamilyFromName(name, handle, out nativeFontFamily);

            GDIPlus.CheckStatus(status);
        }
示例#20
0
        public static void InitializeFonts()
        {
            directWriteFactory = new Factory();
            resourceFontLoader = new Direct2DResourceFontLoader(directWriteFactory);
            fontCollection     = new FontCollection(directWriteFactory, resourceFontLoader, resourceFontLoader.Key);

            for (int i = 0; i < FontDefinitions.Length; i++)
            {
                var def = FontDefinitions[i];
                def.Size = (int)(def.Size * mainWindowScaling);

                var format = new TextFormat(directWriteFactory, def.Name, fontCollection, def.Bold ? FontWeight.Bold : FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, def.Size);

                format.WordWrapping  = WordWrapping.NoWrap;
                format.TextAlignment = def.Alignment == 1 ? TextAlignment.Center : (def.Alignment == 2 ? TextAlignment.Trailing : TextAlignment.Leading);

                if (def.Ellipsis)
                {
                    var trimmingSign = new EllipsisTrimming(directWriteFactory, format);
                    format.SetTrimming(new Trimming()
                    {
                        Delimiter = (int)')', Granularity = TrimmingGranularity.Character, DelimiterCount = 1
                    }, trimmingSign);
                }

                Fonts[i] = format;
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            System.IO.Directory.CreateDirectory("output");
            using (Image <Rgba32> img = new Image <Rgba32>(1500, 500))
            {
                PathBuilder pathBuilder = new PathBuilder();
                pathBuilder.SetOrigin(new PointF(500, 0));
                pathBuilder.AddBezier(new PointF(50, 450), new PointF(200, 50), new PointF(300, 50), new PointF(450, 450));
                // add more complex paths and shapes here.

                IPath path = pathBuilder.Build();

                SixLabors.Fonts.FontCollection fontCollection = new FontCollection();
                SixLabors.Fonts.Font           carlitoFont    = fontCollection.Install(Directory.GetCurrentDirectory() + "/font/Carlito-Regular.ttf")
                                                                .CreateFont(14, FontStyle.Regular);

                string text = "Hello World Hello World Hello World Hello World Hello World";
                var    textGraphicsOptions = new TextGraphicsOptions(true) // draw the text along the path wrapping at the end of the line
                {
                    WrapTextWidth = path.Length
                };

                var point = new PointF(100, 100);
                img.Mutate(ctx => ctx
                           .Fill(Rgba32.White)         // white background image
                           .Draw(Rgba32.Gray, 3, path) // draw the path so we can see what the text is supposed to be following
                           .DrawText(textGraphicsOptions, text, carlitoFont, Rgba32.Black, point));

                img.Save("output/path.png");
            }
        }
        private void PopulateFonts()
        {
            Task.Run(() =>
            {
                var fonts = new FontCollection();

                var fontPaths = Directory.EnumerateFiles("/Library/Fonts", "*.ttf");

                foreach (var item in fontPaths)
                {
                    try
                    {
                        var fontFamily = fonts.Install(item);
                    }
                    catch (InvalidFontFileException)
                    {
                        Trace.WriteLine($"Ops, I couldn't load {item}");
                    }
                }

                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    _fontsDropDown.Items        = fonts.Families;
                    var firstFontFamily         = fonts.Families.FirstOrDefault();
                    _fontsDropDown.SelectedItem = firstFontFamily;
                });
            });
        }
示例#23
0
文件: FontFamily.cs 项目: ash2005/z
        private void CreateFontFamily(string name, FontCollection fontCollection)
        {
            IntPtr fontfamily           = IntPtr.Zero;
            IntPtr nativeFontCollection = (fontCollection == null) ? IntPtr.Zero : fontCollection.nativeFontCollection;

            int status = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, nativeFontCollection), out fontfamily);

            if (status != SafeNativeMethods.Gdip.Ok)
            {
                if (createDefaultOnFail)
                {
                    fontfamily = GetGdipGenericSansSerif();  // This throws if failed.
                }
                else
                {
                    // Special case this incredibly common error message to give more information
                    if (status == SafeNativeMethods.Gdip.FontFamilyNotFound)
                    {
                        throw new ArgumentException(SR.GetString(SR.GdiplusFontFamilyNotFound, name));
                    }
                    else if (status == SafeNativeMethods.Gdip.NotTrueTypeFont)
                    {
                        throw new ArgumentException(SR.GetString(SR.GdiplusNotTrueTypeFont, name));
                    }
                    else
                    {
                        throw SafeNativeMethods.Gdip.StatusException(status);
                    }
                }
            }

            SetNativeFamily(fontfamily);
        }
示例#24
0
        public static Font CreateFont(string text)
        {
            var  fc = new FontCollection();
            Font d  = fc.Install(new FakeFontInstance(text), CultureInfo.InvariantCulture).CreateFont(12);

            return(new Font(d, 1));
        }
示例#25
0
        /// <summary>
        /// Image process and writes to <paramref name="output"/> <see cref="Stream"/>.
        /// </summary>
        /// <param name="output">The output <see cref="Stream"/> to write to.</param>
        /// <param name="firstName">First name to use.</param>
        /// <param name="lastName">Last name to use.</param>
        /// <param name="size">Image size.</param>
        /// <param name="jpeg">Specifies whether the image has .jpg extension.</param>
        /// <param name="background">The background color to use.</param>
        public void Generate(Stream output, string firstName, string lastName, int size = 192, bool jpeg = false, string background = null)
        {
            var avatarText  = string.Format("{0}{1}", firstName?.Length > 0 ? firstName[0] : ' ', lastName?.Length > 0 ? lastName[0] : ' ').ToUpper().RemoveDiacritics();
            var randomIndex = $"{firstName}{lastName}".ToCharArray().Sum(x => x) % _backgroundColours.Length;
            var accentColor = _backgroundColours[randomIndex];

            if (background != null)
            {
                accentColor = new AvatarColor(background);
            }
            using (var image = new Image <Rgba32>(size, size)) {
                image.Mutate(x => x.Fill(accentColor.Background));
                var fonts = new FontCollection();
                // For production application we would recomend you create a FontCollection singleton and manually install the ttf fonts yourself as using SystemFonts can be expensive and you risk font existing or not existing on a deployment by deployment basis.
                var font = _openSansFont.CreateFont("Open Sans", 70, FontStyle.Regular); // for scaling water mark size is largly ignored.
                // Measure the text size.
                var textSize = TextMeasurer.Measure(avatarText, new RendererOptions(font));
                // Find out how much we need to scale the text to fill the space (up or down).
                var scalingFactor = Math.Min(image.Width * 0.6f / textSize.Width, image.Height * 0.6f / textSize.Height);
                // Create a new font.
                var scaledFont         = new Font(font, scalingFactor * font.Size);
                var center             = new PointF(image.Width / 2, image.Height / 2);
                var textGraphicOptions = new TextGraphicsOptions(true)
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center
                };
                image.Mutate(x => x.DrawText(textGraphicOptions, avatarText, scaledFont, accentColor.Color, center));
                image.Save(output, jpeg ? (IImageFormat)JpegFormat.Instance : PngFormat.Instance);
            }
            output.Seek(0, SeekOrigin.Begin);
        }
示例#26
0
        public FontManager(string languageName, StringComparer fontNameComparer)
        {
            var assembly = Assembly.GetExecutingAssembly();

            // For the json file, I think it's better to leave it on the disk
            // (instead of embedding it) so users can edit it
            using var assemblyFileSystem = new FileSystem(Path.GetDirectoryName(assembly.Location));
            using var fileSystem         = new FileSystem(Environment.CurrentDirectory, assemblyFileSystem);

            var fontFallbackSettingsJson  = "{}";
            var fontFallbackSettingsEntry = fileSystem.GetFile("Content/Fonts/FontFallbackSettings.json");

            if (fontFallbackSettingsEntry != null || true)
            {
                Logger.Info($"FontFallback Settings loaded from {fontFallbackSettingsEntry.FullFilePath}");
                using var stream         = fontFallbackSettingsEntry.Open();
                using var reader         = new StreamReader(stream, Encoding.UTF8);
                fontFallbackSettingsJson = reader.ReadToEnd();
            }

            _cachedFonts          = new Dictionary <FontKey, Font>();
            _fontFallbackSettings = FontFallbackSettings
                                    .LoadFromJson(fontFallbackSettingsJson)
                                    .LoadLanguageSpecificFallbackSettings(languageName, fontNameComparer);
            _fallbackFonts = new FontCollection();


            var fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{FallbackEmbeddedFont}-Regular.ttf");

            _fallbackFonts.Install(fontStream);
            fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{FallbackEmbeddedFont}-Bold.ttf");
            _fallbackFonts.Install(fontStream);
        }
示例#27
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="palette">The color palette to use.</param>
 public AvatarGenerator(params AvatarColor[] palette)
 {
     // https://www.materialpalette.com
     if (palette == null || palette.Length == 0)
     {
         _backgroundColours = new[] {
             new AvatarColor("f44336", "ffffff"), // red
             new AvatarColor("e91e63", "ffffff"), // pink
             new AvatarColor("9c27b0", "ffffff"), // purple
             new AvatarColor("673ab7", "ffffff"), // deep-purple
             new AvatarColor("3f51b5", "ffffff"), // indigo
             new AvatarColor("2196f3", "ffffff"), // blue
             new AvatarColor("03a9f4", "ffffff"), // light-blue
             new AvatarColor("00bcd4", "ffffff"), // cyan
             new AvatarColor("009688", "ffffff"), // teal
             new AvatarColor("4caf50", "ffffff"), // green
             new AvatarColor("8bc34a", "ffffff"), // light-green
             new AvatarColor("cddc39", "000000"), // lime
             new AvatarColor("ffeb3b", "000000"), // yellow
             new AvatarColor("ffc107", "000000"), // amber
             new AvatarColor("ff9800", "000000"), // orange
             new AvatarColor("ff5722", "ffffff"), // deep-orange
             new AvatarColor("795548", "ffffff"), // brown
             new AvatarColor("bdbdbd", "000000"), // grey
             new AvatarColor("607d8b", "ffffff"), // blue-grey
         };
     }
     else
     {
         _backgroundColours = palette;
     }
     _openSansFont = new FontCollection();
     _openSansFont.Install(GetFontResourceStream("open-sans", "OpenSans-Regular.ttf"));
 }
示例#28
0
        public static string GenerateCaptchaBase64Image(string code)
        {
            var positions = new List <byte> {
                15, 7, 16, 23, 13
            };

            positions = ShuffleList(positions);

            var fonts  = new FontCollection();
            var font   = fonts.Install("arial.ttf");
            var _font  = font.CreateFont(16, FontStyle.Italic);
            var stream = new MemoryStream();

            using (var img = new Image <Rgba32>(80, 40))
            {
                img.Mutate(x => x.DrawLines(Rgba32.Gray, 2, new PointF(0, 10), new PointF(80, 10)));
                img.Mutate(x => x.DrawLines(Rgba32.Gray, 2, new PointF(0, 30), new PointF(80, 30)));
                for (var i = 0; i < code.Length; ++i)
                {
                    img.Mutate(x => x.DrawText(code.Substring(i, 1), _font, Rgba32.Black, new PointF(i * 15 + 5, positions[i])));
                }

                img.SaveAsPng(stream);
            }

            return(Convert.ToBase64String(stream.GetBuffer()));
        }
示例#29
0
        public static Font CreateFont(string text)
        {
            FontCollection fc = new FontCollection();
            Font           d  = fc.Install(new FakeFontInstance(text)).CreateFont(12);

            return(new Font(d, 1));
        }
示例#30
0
        /// <summary>
        /// 初始化字体池
        /// </summary>
        /// <param name="fontSize">一个初始大小</param>
        private void initFonts(int fontSize)
        {
            if (_fontArr == null)
            {
                var fontDir = "./fonts";
                var list    = new List <Font>();

                if (Directory.Exists(fontDir))
                {
                    var fontFiles      = Directory.GetFiles(fontDir, "*.ttf");
                    var fontCollection = new FontCollection();

                    if (fontFiles?.Length > 0)
                    {
                        foreach (var ff in fontFiles)
                        {
                            list.Add(new Font(fontCollection.Install(ff), fontSize));
                        }
                    }
                }
                else
                {
                    throw new Exception($"绘制验证码字体文件不存在,请将字体文件(.ttf)复制到目录:{fontDir}");
                }
                _fontArr = list.ToArray();
            }
        }
示例#31
0
        /// <summary>
        /// Creates Stylesheet from collections of border styles, fontstyles, color styles etc...
        /// </summary>        
        public static Stylesheet GetStyleSheet(ExcelType scheme)
        {
            var stylesheet = new Stylesheet();
            var fontCollection = new FontCollection();
            var fillsCollection = new FillsCollection();
            var borderCollection = new BorderCollection();
            var cellStyleFormats = new CellStyleFormats();

            var cellStyle = new CellFormat();
            cellStyle.NumberFormatId = 0;
            cellStyle.FontId = 0;
            cellStyle.FillId = 0;
            cellStyle.BorderId = 0;
            cellStyleFormats.Append(cellStyle);
            cellStyleFormats.Count = UInt32Value.FromUInt32((uint)cellStyleFormats.ChildElements.Count);

            var numberingFormats = new CellContentFormat();

            var cellFormats = new DocumentFormat.OpenXml.Spreadsheet.CellFormats();
            cellFormats.Append(GetStyleSheetScheme(scheme));
            cellFormats.Count = UInt32Value.FromUInt32((uint)cellFormats.ChildElements.Count);

            stylesheet.Append(numberingFormats);
            stylesheet.Append(fontCollection);
            stylesheet.Append(fillsCollection);
            stylesheet.Append(borderCollection);
            stylesheet.Append(cellStyleFormats);
            stylesheet.Append(cellFormats);

            var css = new DocumentFormat.OpenXml.Spreadsheet.CellStyles();
            var cs = new CellStyle();
            cs.Name = StringValue.FromString("Normal");
            cs.FormatId = 0;
            cs.BuiltinId = 0;
            css.Append(cs);
            css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
            stylesheet.Append(css);

            var dfs = new DifferentialFormats();
            dfs.Count = 0;
            stylesheet.Append(dfs);

            var tss = new TableStyles();
            tss.Count = 0;
            tss.DefaultTableStyle = StringValue.FromString("TableStyleMedium9");
            tss.DefaultPivotStyle = StringValue.FromString("PivotStyleLight16");
            stylesheet.Append(tss);

            return stylesheet;
        }
        public AssetManager(Game game)
            : base(game)
        {
            _textures = new TextureCollection();
            _fonts = new FontCollection();
            _effects = new EffectCollection();
            _skeletons = new SkeletonCollection();

            _content = new ElegyEngine.Content.ExclusiveContentManager(game.Services);

            _textureLoad = false;
            _effectLoad = false;
            _fontLoad = false;
            _skeletonLoad = false;

            _frameCaptured = false;
        }
 public GameMakerFile()
 {
     Sprites = new SpriteCollection();
       Sounds = new SoundCollection();
       Backgrounds = new BackgroundCollection();
       Paths = new PathCollection();
       Scripts = new ScriptCollection();
       Fonts = new FontCollection();
       TimeLines = new TimeLineCollection();
       Objects = new ObjectCollection();
       Rooms = new RoomCollection();
       Triggers = new TriggerCollection();
       Includes = new IncludedFileCollection();
       Constants = new ConstantCollection();
       Information = new GameInformation();
       Settings = new GameSettings();
       ResourceTree = new ResourceTree();
 }
示例#34
0
 protected abstract void ProcessResource( FontCollection aFonts );
示例#35
0
        private void Load(CompoundFile doc)
        {
            Stream stream;
            try
            {
                // see if workbook works
                stream = doc.OpenStream("Workbook");
            }
            catch (IOException)
            {
                // see if book works, if not then leak the exception
                stream = doc.OpenStream("Book");
            }

            SstRecord sst = null;
            /* long sstPos = 0; */

            // record position dictionary
            SortedList<long, Biff> records = new SortedList<long, Biff>();

            _styles = new StyleCollection(this);
            _formats = new FormatCollection(this);
            _fonts = new FontCollection(this);
            _palette = new Palette(this);
            _hyperLinks = new HyperLinkCollection(this);

            while (stream.Length - stream.Position >= GenericBiff.MinimumSize)
            {
                // capture the current stream position
                long pos = stream.Position;

                // decode the record if possible
                Biff record = GetCorrectRecord(new GenericBiff(stream), stream, sst);

                // capture 
                // shared string table 
                if (record is SstRecord)
                {
                    Debug.Assert(sst == null);
                    sst = (SstRecord)record;
                    /* sstPos = pos; */
                }
                // formatting records
                else if (record is FormatRecord)
                {
                    FormatRecord f = (FormatRecord)record;
                    _formats.Add(f.Index, new Format(this, f));
                }
                else if (record is FontRecord)
                    _fonts.Add(new Font(this, (FontRecord)record));
                else if (record is PaletteRecord)
                    _palette.Initialize((PaletteRecord)record);
                else if (record is XfRecord)
                    _styles.Add(new Style(this, (XfRecord)record));
                else if (record is HyperLinkRecord)
                    _hyperLinks.Add((HyperLinkRecord)record);

                Debug.Assert(!records.ContainsKey(pos));
                // store the position and corresponding record
                records[pos] = record;
            }

            // generate the worksheets
            _sheets = new WorksheetCollection();
            foreach (Biff record in records.Values)
            {
                if (record is BoundSheetRecord)
                    _sheets.Add(new Worksheet(this, (BoundSheetRecord)record, records));
            }
        }
示例#36
0
        protected override void ProcessResource( FontCollection aFonts )
        {
            if ( !aFonts.Any() )
            return;

              OnCategoryProcessing( ResourceTypes.Fonts );
              Directory.CreateDirectory( Directories.Fonts );
              var previous = SetCurrentDirectory( Directories.Fonts );

              foreach ( var font in aFonts ) {
            var document =
              new XElement( "Font",
            CreateIndexedResourceNodes( font ),
            new XElement( "FontFamily", font.FontFamily ),
            new XElement( "Size", font.Size ),
            new XElement( "Bold", font.Bold ),
            new XElement( "Italic", font.Italic ),
            new XElement( "CharacterRangeLow", font.CharacterRangeLow ),
            new XElement( "CharacterRangeHigh", font.CharacterRangeHigh ),
            new XElement( "CharacterSet", font.CharacterSet ),
            new XElement( "AntiAliasing", font.AntiAliasing )
              );

            OnResourceProcessed( font.Name );
            SaveDocument( document, SafeResourceFilename( font ) + ".xml" );
              }

              OnCategoryProcessed( ResourceTypes.Fonts );
              SetCurrentDirectory( previous );
        }
示例#37
0
 static Fonts()
 {
     Cache = new FontCollection();
 }