コード例 #1
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: 1
            string fileName = dataDir + "courier.pfb"; //Font file name with full path

            FontDefinition fd   = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
            Type1Font      font = Aspose.Font.Font.Open(fd) as Type1Font;

            bool latinText = true;


            for (uint code = 65; code < 123; code++)
            {
                GlyphId gid = font.Encoding.DecodeToGid(code);
                if (gid == null || gid == GlyphUInt32Id.NotDefId)
                {
                    latinText = false;
                }
            }

            if (latinText)
            {
                Console.WriteLine(string.Format("Font {0} supports latin symbols.", font.FontName));
            }
            else
            {
                Console.WriteLine(string.Format("Latin symbols are not supported by font {0}.", font.FontName));
            }
            //ExEnd: 1
        }
コード例 #2
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Handles the SelectedIndexChanged event of the cbDefaultNormalFont control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        /// ------------------------------------------------------------------------------------
        private void m_defaultFontComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_ws == null)
            {
                return;
            }
            string oldFont = m_ws.DefaultFontName;

            if (oldFont != m_defaultFontComboBox.Text)
            {
                // Finding a font missing should not result in persisting a font name change
                if (string.Format(FwCoreDlgControls.kstidMissingFontFmt, oldFont) != m_defaultFontComboBox.Text)
                {
                    FontDefinition font;
                    if (!m_ws.Fonts.TryGet(m_defaultFontComboBox.Text, out font))
                    {
                        font = new FontDefinition(m_defaultFontComboBox.Text);
                    }
                    m_ws.DefaultFont = font;
                }

                if (m_ws.DefaultFont != null)
                {
                    m_defaultFontFeaturesButton.FontName     = m_defaultFontComboBox.Text;
                    m_defaultFontFeaturesButton.FontFeatures = m_ws.DefaultFont.Features;
                }

                bool isGraphiteFont = m_defaultFontFeaturesButton.IsGraphiteFont;
                m_graphiteGroupBox.Enabled          = isGraphiteFont;
                m_ws.IsGraphiteEnabled              = false;
                m_enableGraphiteCheckBox.Checked    = false;
                m_defaultFontFeaturesButton.Enabled = false;
            }
        }
コード例 #3
0
        public override void Initialize(IResolver resolver)
        {
            var fontDef = new FontDefinition("DefaultFont", 12);

            this.lbl = new Label(fontDef)
            {
                FontSize  = 12,
                Alignment = TextAlignment.Left,
                Tint      = Color.White,
                Text      = this.Text
            };
            this.Add(this.lbl);

            var inst = new NinePatchInstruction
            {
                TopLeft      = new Rectangle(0, 0, 12, 12),
                TopCenter    = new Rectangle(12, 0, 8, 12),
                TopRight     = new Rectangle(20, 0, 12, 12),
                MiddleLeft   = new Rectangle(0, 12, 12, 8),
                MiddleCenter = new Rectangle(12, 12, 16, 16),
                MiddleRight  = new Rectangle(20, 12, 12, 8),
                BottomLeft   = new Rectangle(0, 20, 12, 12),
                BottomCenter = new Rectangle(12, 20, 8, 12),
                BottomRight  = new Rectangle(20, 20, 12, 12),
            };

            this.patch = new NinePatchSprite(new TextureAssetInstruction {
                Asset = "ninepatch"
            }, inst);
            this.lbl.Components.Add(this.patch);

            this.Opacity = this.Opacity;

            base.Initialize(resolver);
        }
コード例 #4
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();

            //ExStart: 1
            string fileName = dataDir + "Montserrat-Regular.ttf"; //Font file name with full path

            FontDefinition fd   = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
            TtfFont        font = Aspose.Font.Font.Open(fd) as TtfFont;

            string name = font.FontName;

            Console.WriteLine("Font name: " + name);
            Console.WriteLine("Glyph count: " + font.NumGlyphs);
            string metrics = string.Format(
                "Font metrics: ascender - {0}, descender - {1}, typo ascender = {2}, typo descender = {3}, UnitsPerEm = {4}",
                font.Metrics.Ascender, font.Metrics.Descender,
                font.Metrics.TypoAscender, font.Metrics.TypoDescender, font.Metrics.UnitsPerEM);

            Console.WriteLine(metrics);

            //Get cmap unicode encoding table from font as object TtfCMapFormatBaseTable to access information about font glyph for symbol 'A'.
            //Also check that font has object TtfGlyfTable (table 'glyf') to access glyph.
            Aspose.Font.TtfCMapFormats.TtfCMapFormatBaseTable cmapTable = null;
            if (font.TtfTables.CMapTable != null)
            {
                cmapTable = font.TtfTables.CMapTable.FindUnicodeTable();
            }
            if (cmapTable != null && font.TtfTables.GlyfTable != null)
            {
                Console.WriteLine("Font cmap unicode table: PlatformID = " + cmapTable.PlatformId + ", PlatformSpecificID = " + cmapTable.PlatformSpecificId);

                //Code for 'A' symbol
                char unicode = (char)65;

                //Glyph index for 'A'
                uint glIndex = cmapTable.GetGlyphIndex(unicode);

                if (glIndex != 0)
                {
                    //Glyph for 'A'
                    Glyph glyph = font.GetGlyphById(glIndex);
                    if (glyph != null)
                    {
                        //Print glyph metrics
                        Console.WriteLine("Glyph metrics for 'A' symbol:");
                        string bbox = string.Format(
                            "Glyph BBox: Xmin = {0}, Xmax = {1}" + ", Ymin = {2}, Ymax = {3}",
                            glyph.GlyphBBox.XMin, glyph.GlyphBBox.XMax,
                            glyph.GlyphBBox.YMin, glyph.GlyphBBox.YMax);
                        Console.WriteLine(bbox);
                        Console.WriteLine("Width:" + font.Metrics.GetGlyphWidth(new GlyphUInt32Id(glIndex)));
                    }
                }
            }
            //ExEnd: 1
        }
コード例 #5
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: 1
            string fileName = dataDir + "Montserrat-Regular.ttf"; //Font file name with full path

            FontDefinition fd      = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
            TtfFont        ttfFont = Aspose.Font.Font.Open(fd) as TtfFont;
            //ExEnd: 1
        }
コード例 #6
0
        public static void LoadCffFromByteArray()
        {
            string dataDir = RunExamples.GetDataDir_Data();

            //ExStart: LoadCffFromByteArray
            byte[]         fontMemoryData = File.ReadAllBytes(dataDir + "OpenSans-Regular.cff");
            FontDefinition fd             = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new ByteContentStreamSource(fontMemoryData)));
            CffFont        cffFont        = Aspose.Font.Font.Open(fd) as CffFont;
            //ExEnd: LoadCffFromByteArray
        }
コード例 #7
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: LoadCFFFromDisc
            string fileName = dataDir + "OpenSans-Regular.cff"; //Font file name with full path

            FontDefinition fd      = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new FileSystemStreamSource(fileName)));
            CffFont        ttfFont = Aspose.Font.Font.Open(fd) as CffFont;
            //ExEnd: LoadCFFFromDisc
        }
コード例 #8
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: 1
            string fileName = dataDir + "courier.pfb"; //Font file name with full path

            FontDefinition fd   = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
            Type1Font      font = Aspose.Font.Font.Open(fd) as Type1Font;
            //ExEnd: 1
        }
コード例 #9
0
        public void CurrentDefaultFontName_SetSameFontDifferentCase_NotUpdated()
        {
            var font = new FontDefinition("Test");

            _model.AddPredefinedDefinition(new WritingSystemDefinition("pt")
            {
                DefaultFont = font
            });
            _model.CurrentDefaultFontName = "test";
            Assert.That(_model.CurrentDefaultFontName, Is.EqualTo("Test"));
        }
コード例 #10
0
                    /// <summary>
                    /// Initializes a new font using the given API data.
                    /// </summary>
                    public Font(FontDefinition fontData, int index) : this(fontData.Item1, fontData.Item2, index)
                    {
                        var styleData = fontData.Item3;

                        for (int n = 0; n < 2; n++)
                        {
                            if (styleData[n].Item4 != null)
                            {
                                TryAddStyle(styleData[n]);
                            }
                        }
                    }
コード例 #11
0
                /// <summary>
                /// Used publicly to register a new font via the API. Returns font accessors.
                /// </summary>
                private static FontMembers?TryAddApiFont(FontDefinition fontData)
                {
                    IFont font;

                    if (TryAddFont(fontData, out font))
                    {
                        return(font.GetApiData());
                    }
                    else
                    {
                        return(null);
                    }
                }
コード例 #12
0
        public static void Run()
        {
            //ExStart: 1
            string dataDir = RunExamples.GetDataDir_Data();
            //Font to check
            string fileName = dataDir + "Montserrat-Regular.ttf"; //Font file name with full path

            FontDefinition fd           = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
            TtfFont        font         = Aspose.Font.Font.Open(fd) as TtfFont;
            LicenseFlags   licenseFlags = null;

            if (font.TtfTables.Os2Table != null)
            {
                licenseFlags = font.TtfTables.Os2Table.GetLicenseFlags();
            }

            if (licenseFlags == null || licenseFlags.FSTypeAbsent)
            {
                Console.WriteLine(string.Format("Font {0} has no embedded license restrictions", font.FontName));
            }
            else
            {
                if (licenseFlags.IsEditableEmbedding)
                {
                    Console.WriteLine(
                        string.Format("Font {0} may be embedded, and may be temporarily loaded on other systems.", font.FontName)
                        + " In addition, editing is permitted, including ability to format new text"
                        + " using the embedded font, and changes may be saved.");
                }
                else if (licenseFlags.IsInstallableEmbedding)
                {
                    Console.WriteLine(
                        string.Format("Font {0} may be embedded, and may be permanently installed", font.FontName)
                        + " for use on a remote systems, or for use by other users.");
                }
                else if (licenseFlags.IsPreviewAndPrintEmbedding)
                {
                    Console.WriteLine(
                        string.Format("Font {0} may be embedded, and may be temporarily loaded", font.FontName)
                        + "  on other systems for purposes of viewing or printing the document.");
                }
                else if (licenseFlags.IsRestrictedLicenseEmbedding)
                {
                    Console.WriteLine(
                        string.Format("Font {0} must not be modified, embedded or exchanged in any manner", font.FontName)
                        + " without first obtaining explicit permission of the legal owner.");
                }
            }
            //ExEnd: 1
        }
コード例 #13
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: 1
            string fileName = dataDir + "courier.pfb"; //Font file name with full path

            FontDefinition fd   = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
            Type1Font      font = Aspose.Font.Font.Open(fd) as Type1Font;


            DrawText("Hello world", font, 14, Brushes.White, Brushes.Black, dataDir + "hello1_type1_out.jpg");
            DrawText("Hello world", font, 14, Brushes.Yellow, Brushes.Red, dataDir + "hello2_type1_out.jpg");
            //ExEnd: 1
        }
コード例 #14
0
        private Label CreateLabel(string text, Color textColor)
        {
            var fontDef = new FontDefinition("DefaultFont", 12);
            var lbl     = new Label(fontDef)
            {
                FontSize  = 12,
                Alignment = TextAlignment.Left,
                Tint      = textColor,
                Text      = text
            };

            this.UiRoot.Add(lbl);
            return(lbl);
        }
コード例 #15
0
                /// <summary>
                /// Attempts to register a new font using API data. Returns the font created.
                /// </summary>
                public static bool TryAddFont(FontDefinition fontData, out IFont font)
                {
                    if (!Instance.fonts.Exists(x => x.Name == fontData.Item1))
                    {
                        font = new Font(fontData, Instance.fonts.Count);
                        Instance.fonts.Add(font);

                        return(true);
                    }
                    else
                    {
                        font = null;
                        return(false);
                    }
                }
コード例 #16
0
        public void CurrentDefaultFontName_DifferentFontName_DefaultFontNotUpdatedUntilSave()
        {
            var font = new FontDefinition("Test");

            _model.AddPredefinedDefinition(new WritingSystemDefinition("pt")
            {
                DefaultFont = font
            });
            _model.CurrentDefaultFontName = "NewFont";
            Assert.That(_model.CurrentDefaultFontName, Is.EqualTo("NewFont"));
            Assert.That(_model.CurrentDefinition.DefaultFont, Is.EqualTo(font));
            _model.Save();
            Assert.That(_model.CurrentDefinition.DefaultFont.Name, Is.EqualTo("NewFont"));
            Assert.That(_model.CurrentDefinition.Fonts.Count, Is.EqualTo(2));
        }
コード例 #17
0
                /// <summary>
                /// Attempts to register a new font using API data. Returns the font created.
                /// </summary>
                public static bool TryAddFont(FontDefinition fontData, out IFontMin font)
                {
                    FontMembers?members = Instance.TryAddFontFunc(fontData);

                    if (members != null)
                    {
                        font = new FontData(members.Value);
                        return(true);
                    }
                    else
                    {
                        font = null;
                        return(false);
                    }
                }
コード例 #18
0
        public static void Run()
        {
            //ExStart: 2
            string dataDir = RunExamples.GetDataDir_Data();

            string         fileName1 = dataDir + "Montserrat-Bold.ttf"; //Font file name with full path
            FontDefinition fd1       = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName1)));
            TtfFont        ttfFont1  = Aspose.Font.Font.Open(fd1) as TtfFont;

            string         fileName2 = dataDir + "Lora-Bold.ttf"; //Font file name with full path
            FontDefinition fd2       = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName2)));
            TtfFont        ttfFont2  = Aspose.Font.Font.Open(fd2) as TtfFont;

            DrawText("Hello world", ttfFont1, 14, Brushes.White, Brushes.Black, dataDir + "hello1_montserrat_out.jpg");
            DrawText("Hello world", ttfFont2, 14, Brushes.Yellow, Brushes.Red, dataDir + "hello2_lora_out.jpg");
            //ExEnd: 2
        }
コード例 #19
0
        public static void Run()
        {
            //ExStart: 1
            //byte array to load Font from
            string dataDir = RunExamples.GetDataDir_Data();

            byte[]         fontMemoryData = File.ReadAllBytes(dataDir + "Montserrat-Regular.ttf");
            FontDefinition fd             = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new ByteContentStreamSource(fontMemoryData)));
            TtfFont        ttfFont        = Aspose.Font.Font.Open(fd) as TtfFont;

            //Work with data from just loaded TtfFont object

            //Save CffFont to disk
            //Output Font file name with full path
            string outputFile = RunExamples.GetDataDir_Data() + "Montserrat-Regular_out.ttf";

            ttfFont.Save(outputFile);
            //ExEnd: 1
        }
コード例 #20
0
        private IEnumerable <FontDescription> GetDescriptionsForAsset(FontDefinition definition)
        {
            var fontNames = string.IsNullOrEmpty(definition.FontName) ? "Arial" : definition.FontName;

            foreach (var fontName in fontNames.Split(','))
            {
                var fontDesc = new FontDescription(
                    fontName,
                    definition.FontSize,
                    definition.Spacing,
                    FontDescriptionStyle.Regular,
                    definition.UseKerning);

                if (definition.CharacterRanges == null || definition.CharacterRanges.Length == 0)
                {
                    // Add the entire ASCII range of characters to the sprite font.
                    for (var c = 0; c < 256; c++)
                    {
                        fontDesc.Characters.Add((char)c);
                    }
                }
                else
                {
                    foreach (var range in definition.CharacterRanges)
                    {
                        for (var c = range.Start; c <= range.End; c++)
                        {
                            fontDesc.Characters.Add((char)c);
                        }
                    }
                }

#if PLATFORM_LINUX
                fontDesc.Identity = new ContentIdentity
                {
                    SourceFilename = "/usr/share/fonts/truetype/dummy.spritefont"
                };
#endif
                yield return(fontDesc);
            }
        }
コード例 #21
0
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Data();
            //ExStart: 1
            string fileName = dataDir + "courier.pfb"; //Font file name with full path

            FontDefinition fd   = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
            Type1Font      font = Aspose.Font.Font.Open(fd) as Type1Font;

            string name = font.FontName;

            Console.WriteLine("Font name: " + name);
            Console.WriteLine("Glyph count: " + font.NumGlyphs);
            string metrics = string.Format(
                "Font metrics: ascender - {0}, descender - {1}, typo ascender = {2}, typo descender = {3}, UnitsPerEm = {4}",
                font.Metrics.Ascender, font.Metrics.Descender,
                font.Metrics.TypoAscender, font.Metrics.TypoDescender, font.Metrics.UnitsPerEM);

            Console.WriteLine(metrics);
            //ExEnd: 1
        }
コード例 #22
0
        private void InitUi()
        {
            var fontDef = new FontDefinition("DefaultFont24", 24);

            this.lblScore = new Label(fontDef)
            {
                FontSize          = 24,
                Text              = $"Score: {this.score}",
                Alignment         = TextAlignment.Center,
                LocalPosition     = new Vector2(Resolution.VirtualScreen.X / 2, 50),
                DropShadowOffset  = new Vector2(2, 1),
                DropShadowTint    = Color.White,
                DropShadowOpacity = .6f,
                HasDropShadow     = true
            };
            this.UiRoot.Add(this.lblScore);

            var bar = new HealthBar(this.playerVm);

            this.UiRoot.Add(bar);
        }
コード例 #23
0
ファイル: FontGenerators.cs プロジェクト: glynford/EgoPDF
        public FontDefinition LoadFont(string name, string path)
        {
            var font     = new GlyphTypeface(new Uri("file:///" + path));
            var fontData = new FontDefinition
            {
                FontType = FontTypeEnum.TrueType,
                FontFile = path,
                Name     = font.FamilyNames.FirstOrDefault().Value.ToLower(),
            };

            foreach (var advance in font.AdvanceWidths)
            {
                var leftBearing  = font.LeftSideBearings[advance.Key];
                var rightBearing = font.RightSideBearings[advance.Key];
                fontData.Widths[Convert.ToChar(advance.Key).ToString()] = advance.Value * 1000;
            }

            FontBuilder.Fonts[name.ToLower()] = fontData;

            return(fontData);
        }
コード例 #24
0
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object?existingValue, JsonSerializer serializer)
        {
            var obj = JToken.Load(reader);

            if (obj.Type != JTokenType.Object)
            {
                return(null);
            }

            FontDefinition fontDefinition = null;

            //var jObject = (JObject)obj;

            //	return Decode180(jObject, serializer);
            var jObject = (JObject)obj;

            if (jObject.TryGetValue(
                    "type", StringComparison.InvariantCultureIgnoreCase, out var definitionType))
            {
                switch (definitionType.Value <string>())
                {
                case "bitmap":
                    fontDefinition = jObject.ToObject <BitmapFontDefinition>();
                    break;

                case "legacy_unicode":
                    fontDefinition = jObject.ToObject <LegacyFontDefinition>();
                    break;

                default:
                    Log.Warn($"Unknown font definition type: {definitionType.Value<string>()}");
                    return(null);
                }
            }

            return(fontDefinition);
        }
コード例 #25
0
ファイル: LdmlDataMapper.cs プロジェクト: jwickberg/libpalaso
		private void ReadFontElement(XElement externalResourcesElem, WritingSystemDefinition ws)
		{
			foreach (XElement fontElem in externalResourcesElem.NonAltElements(Sil + "font"))
			{
				var fontName = (string) fontElem.Attribute("name");
				if (!string.IsNullOrEmpty(fontName))
				{
					var fd = new FontDefinition(fontName);

					// Types (space separate list)
					var roles = (string) fontElem.Attribute("types");
					if (!String.IsNullOrEmpty(roles))
					{
						IEnumerable<string> roleList = roles.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
						foreach (string roleEntry in roleList)
						{
							fd.Roles |= RoleToFontRoles[roleEntry];
						}
					}
					else
					{
						fd.Roles = FontRoles.Default;
					}

					// Relative Size
					fd.RelativeSize = (float?) fontElem.Attribute("size") ?? 1.0f;

					// Minversion
					fd.MinVersion = (string) fontElem.Attribute("minversion");

					// Features (space separated list of key=value pairs)
					fd.Features = (string) fontElem.Attribute("features");

					// Language
					fd.Language = (string) fontElem.Attribute("lang");

					// OpenType language
					fd.OpenTypeLanguage = (string) fontElem.Attribute("otlang");

					// Font Engine (space separated list) supercedes legacy isGraphite flag
					// If attribute is missing it is assumed to be "gr ot"
					var engines = (string) fontElem.Attribute("engines") ?? "gr ot";
					IEnumerable<string> engineList = engines.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
					foreach (string engineEntry in engineList)
						fd.Engines |= (EngineToFontEngines[engineEntry]);

					// Subset
					fd.Subset = (string) fontElem.Attribute("subset");

					// URL elements
					foreach (XElement urlElem in fontElem.NonAltElements(Sil + "url"))
						fd.Urls.Add(urlElem.Value);

					ws.Fonts.Add(fd);
				}
			}
		}
コード例 #26
0
		public void Roundtrip_LdmlFont()
		{
			using (var environment = new TestEnvironment())
			{
				var fd = new FontDefinition("Padauk")
				{
					RelativeSize = 2.1f,
					MinVersion = "3.1.4",
					Features = "order=3 children=2 color=red createDate=1996",
					Language = "en",
					Engines = FontEngines.Graphite | FontEngines.OpenType,
					OpenTypeLanguage = "abcd",
					Roles = FontRoles.Default | FontRoles.Emphasis,
					Subset = "unknown"
				};
				fd.Urls.Add("http://wirl.scripts.sil.org/padauk");
				fd.Urls.Add("http://scripts.sil.org/cms/scripts/page.php?item_id=padauk");

				var wsToLdml = new WritingSystemDefinition("en", "Latn", "", "");
				wsToLdml.Fonts.Add(fd);

				var ldmlAdaptor = new LdmlDataMapper(new TestWritingSystemFactory());
				ldmlAdaptor.Write(environment.FilePath("test.ldml"), wsToLdml, null);
				AssertThatXmlIn.File(environment.FilePath("test.ldml"))
					.HasAtLeastOneMatchForXpath("/ldml/special/sil:external-resources/sil:font[@name='Padauk' and @types='default emphasis' and @size='2.1' and @minversion='3.1.4' and @features='order=3 children=2 color=red createDate=1996' and @lang='en' and @otlang='abcd' and @subset='unknown']/sil:url[text()='http://wirl.scripts.sil.org/padauk']", environment.NamespaceManager);
				AssertThatXmlIn.File(environment.FilePath("test.ldml"))
					.HasAtLeastOneMatchForXpath("/ldml/special/sil:external-resources/sil:font[@name='Padauk' and @types='default emphasis' and @size='2.1' and @minversion='3.1.4' and @features='order=3 children=2 color=red createDate=1996' and @lang='en' and @otlang='abcd' and @subset='unknown']/sil:url[text()='http://scripts.sil.org/cms/scripts/page.php?item_id=padauk']", environment.NamespaceManager);


				var wsFromLdml = new WritingSystemDefinition();
				ldmlAdaptor.Read(environment.FilePath("test.ldml"), wsFromLdml);

				Assert.That(wsFromLdml.Fonts.First().ValueEquals(fd));
			}
		}
コード例 #27
0
ファイル: Font.cs プロジェクト: Pierre48/ColorConsole
 public virtual string Convert(string str, FontDefinition fontDefinition)
 {
     return(str);
 }
コード例 #28
0
        public override void ApplyFormattingAndLayout(SlotData slotData, SlotStyleData slotStyleData, TableLayoutItemInfo layout)
        {
            base.ApplyFormattingAndLayout(slotData, slotStyleData, layout);

            Brush background = null;
            Brush foreground = null;
            short fontID     = -1;

            //IMPLEMENT: the rest of the properties in SlotData, SlotStyleData, and TableLayoutItemInfo

            if (layout != null)
            {
                // margins and paddings
                Margin  = new Spacing(layout.LeftMargin, layout.TopMargin, layout.RightMargin, layout.BottomMargin);
                Padding = new Spacing(layout.LeftPadding, layout.TopPadding, layout.RightPadding, layout.BottomPadding);

                // cropping
                Crop = layout.CropStrategy;
            }

            if (slotData != null)
            {
                // background
                if (slotData.Background.HasValue)
                {
                    PaintStyleResult bgRes = ResolvePaintStyle(slotData.Background.Value, PaintStyleUse.Background);

                    if (bgRes.Brush != null)
                    {
                        background = bgRes.Brush;
                    }
                }

                // foreground
                if (slotData.Foreground.HasValue)
                {
                    PaintStyleResult fgRes = ResolvePaintStyle(slotData.Foreground.Value, PaintStyleUse.Foreground);

                    if (fgRes.Brush != null)
                    {
                        foreground = fgRes.Brush;
                    }
                }

                // get font
                fontID = slotData.Font ?? -1;
            }

            if (slotStyleData != null)
            {
                // cropping
                Crop = slotStyleData.Crop;

                // background
                if (slotStyleData.Background.HasValue)
                {
                    PaintStyleResult bgRes = ResolvePaintStyle(slotStyleData.Background.Value, PaintStyleUse.Background);

                    if (bgRes.Brush != null)
                    {
                        background = bgRes.Brush;
                    }
                }

                // foreground
                if (slotStyleData.Foreground.HasValue)
                {
                    PaintStyleResult fgRes = ResolvePaintStyle(slotStyleData.Foreground.Value, PaintStyleUse.Foreground);

                    if (fgRes.Brush != null)
                    {
                        foreground = fgRes.Brush;
                    }
                }

                // get font
                fontID = slotStyleData.Font;
            }

            // use parent foreground if needed
            if (foreground == null)
            {
                foreground = Atomic.Foreground;
            }

            // apply brushes
            Background             = background;
            textControl.Foreground = foreground;

            // apply font
            if (fontID != -1)
            {
                FontReferencePaletteEntry fr = Atomic.FindCascadedPaletteItem(fontID) as FontReferencePaletteEntry;

                if (fr != null)
                {
                    FontDefinition fd = fr.Resolve(Atomic.ParentNode.ApplicationID);

                    if (fd != null)
                    {
                        fd.Apply(textControl);
                    }
                }
            }

            // apply cropping, alignment, tick
            if ((Crop & CropStrategy.Wrap) == CropStrategy.Wrap)
            {
                textControl.TextWrapping = TextWrapping.Wrap;

                if ((Crop & CropStrategy.Tick) == CropStrategy.Tick)
                {
                    textControl.TextTrimming = TextTrimming.WordEllipsis;
                }
                else
                {
                    textControl.TextTrimming = TextTrimming.None;
                }
            }
            else if ((Crop & CropStrategy.Tick) == CropStrategy.Tick)
            {
                textControl.TextWrapping = TextWrapping.NoWrap;
                textControl.TextTrimming = TextTrimming.WordEllipsis;
            }
            else
            {
                textControl.TextWrapping = TextWrapping.NoWrap;
                textControl.TextTrimming = TextTrimming.None;
            }

            // set horizontal alignment (vertical one is done in layout)
            if ((Crop & CropStrategy.AlignLeft) == CropStrategy.AlignLeft)
            {
                textControl.TextAlignment = TextAlignment.Left;
            }
            else if ((Crop & CropStrategy.AlignHCenter) == CropStrategy.AlignHCenter)
            {
                textControl.TextAlignment = TextAlignment.Center;
            }
            else if ((Crop & CropStrategy.AlignRight) == CropStrategy.AlignRight)
            {
                textControl.TextAlignment = TextAlignment.Right;
            }
        }
コード例 #29
0
		public void CurrentDefaultFontName_SetSameFontDifferentCase_NotUpdated()
		{
			var font = new FontDefinition("Test");
			_model.AddPredefinedDefinition(new WritingSystemDefinition("pt") {DefaultFont = font});
			_model.CurrentDefaultFontName = "test";
			Assert.That(_model.CurrentDefaultFontName, Is.EqualTo("Test"));
		}
コード例 #30
0
		public void CurrentDefaultFontName_DifferentFontName_DefaultFontNotUpdatedUntilSave()
		{
			var font = new FontDefinition("Test");
			_model.AddPredefinedDefinition(new WritingSystemDefinition("pt") {DefaultFont = font});
			_model.CurrentDefaultFontName = "NewFont";
			Assert.That(_model.CurrentDefaultFontName, Is.EqualTo("NewFont"));
			Assert.That(_model.CurrentDefinition.DefaultFont, Is.EqualTo(font));
			_model.Save();
			Assert.That(_model.CurrentDefinition.DefaultFont.Name, Is.EqualTo("NewFont"));
			Assert.That(_model.CurrentDefinition.Fonts.Count, Is.EqualTo(2));
		}
		public void Migrate_OriginalFileContainsFwNamespace_InfoIsMigrated()
		{
			using (var environment = new TestEnvironment())
			{
				environment.WriteLdmlFile(
					"test.ldml",
					LdmlContentForTests.Version0WithFw("en", "x-Kala", "x-AP", "1996-x-myOwnVariant"));

				var migrator = new LdmlInFolderWritingSystemRepositoryMigrator(environment.LdmlPath, environment.OnMigrateCallback);
				migrator.Migrate();

				var repo = new TestLdmlInFolderWritingSystemRepository(environment.LdmlPath);
				migrator.ResetRemovedProperties(repo);

				var other = new FontDefinition("Arial") {Features = "order=3 children=2 color=red createDate=1996", Roles = FontRoles.Default};

				var main = new CharacterSetDefinition("main")
				{
					Characters = {
						"α", "Α", "ά", "ὰ", "ᾷ", "ἀ", "Ἀ", "ἁ", "Ἁ", "ἄ", "Ἄ", "ἂ", "ἅ", "Ἅ", "ἃ", "Ἃ", "ᾶ", "ᾳ", "ᾴ", "ἆ", "Ἆ", "ᾄ", "ᾅ", "β", "Β", "γ",
						"Γ", "δ", "Δ", "ε", "Ε", "έ", "ὲ", "ἐ", "Ἐ", "ἑ", "Ἑ", "ἔ", "Ἔ", "ἕ", "Ἕ", "ἓ", "Ἓ", "ζ", "Ζ", "η", "Η", "ή", "ὴ", "ῇ", "ἠ", "Ἠ",
						"ἡ", "Ἡ", "ἤ", "Ἤ", "ἢ", "ἥ", "Ἥ", "Ἢ", "ἣ", "ᾗ", "ῆ", "ῃ", "ῄ", "ἦ", "Ἦ", "ᾖ", "ἧ", "ᾐ", "ᾑ", "ᾔ", "θ", "Θ", "ι", "ί", "ὶ", "ϊ",
						"ΐ", "ῒ", "ἰ", "Ἰ", "ἱ", "Ἱ", "ἴ", "Ἴ", "ἵ", "Ἵ", "ἳ", "ῖ", "ἶ", "ἷ", "κ", "Κ", "λ", "Λ", "μ", "Μ", "ν", "Ν", "ξ", "Ξ", "ο", "Ο",
						"ό", "ὸ", "ὀ", "Ὀ", "ὁ", "Ὁ", "ὄ", "Ὄ", "ὅ", "ὂ", "Ὅ", "ὃ", "Ὃ", "π", "Π", "ρ", "Ρ", "ῥ", "Ῥ", "σ", "ς", "Σ", "τ", "Τ", "υ", "Υ",
						"ύ", "ὺ", "ϋ", "ΰ", "ῢ", "ὐ", "ὑ", "Ὑ", "ὔ", "ὕ", "ὒ", "Ὕ", "ὓ", "ῦ", "ὖ", "ὗ", "Ὗ", "φ", "Φ", "χ", "Χ", "ψ", "Ψ", "ω", "ώ", "ὼ",
						"ῷ", "ὠ", "ὡ", "Ὡ", "ὤ", "Ὤ", "ὢ", "ὥ", "Ὥ", "ᾧ", "ῶ", "ῳ", "ῴ", "ὦ", "Ὦ", "ὧ", "Ὧ", "ᾠ"
					}
				};

				var numeric = new CharacterSetDefinition("numeric") {Characters = {"๐", "๑", "๒", "๓", "๔", "๕", "๖", "๗", "๘", "๙"}};

				var punctuation = new CharacterSetDefinition("punctuation") {Characters = {" ", "-", ",", ".", "’", "«", "»", "(", ")", "[", "]"}};

				WritingSystemDefinition ws = repo.Get("en-Qaaa-QM-1996-x-Kala-AP-myOwnVar");

				Assert.That(ws.DefaultFont.ValueEquals(other));
				Assert.That(ws.WindowsLcid, Is.EqualTo("4321"));
				Assert.That(ws.CharacterSets["main"].ValueEquals(main));
				Assert.That(ws.CharacterSets["numeric"].ValueEquals(numeric));
				Assert.That(ws.CharacterSets["punctuation"].ValueEquals(punctuation));

				// ScriptName, RegionName, VariantName, LegacyMapping, IsGraphiteEnabled
				Assert.That(ws.LegacyMapping, Is.EqualTo("SomeMapper"));
				Assert.That(ws.IsGraphiteEnabled, Is.True);
				Assert.That(ws.Script.Name, Is.EqualTo("scriptName"));
				Assert.That(ws.Region.Name, Is.EqualTo("regionName"));
				Assert.That(ws.Variants[1].Name, Is.EqualTo("aVarName"));
			}
		}
コード例 #32
0
 /// <summary>
 /// Attempts to register a new font using API data.
 /// </summary>
 public static bool TryAddFont(FontDefinition fontData) =>
 Instance.TryAddFontFunc(fontData) != null;
コード例 #33
0
ファイル: BibleTextImage.cs プロジェクト: AntonyCorbett/OnlyV
        public BibleTextImage()
        {
            Width        = 1920;
            Height       = 1080;
            TopMargin    = 100;
            BottomMargin = 100;
            LeftMargin   = 160;
            RightMargin  = 160;

            MainFont = new FontDefinition
            {
                FontSize   = 96,
                FontStyle  = FontStyles.Normal,
                FontFamily = new FontFamily("Georgia"),
                FontColor  = Colors.White
            };

            BackgroundColor = FromHtmlString("#275DAD");

            ShowVerseNumbers = true;
            HorzAlignment    = TextAlignment.Center;

            LineSpacing = OnlyVLineSpacing.Normal;

            ShowTitle = true;

            TitleFont = new FontDefinition
            {
                FontSize   = (MainFont.FontSize * 3) / 4,
                FontFamily = MainFont.FontFamily,
                FontStyle  = FontStyles.Italic,
                FontColor  = FromHtmlString("#FCBA04")
            };

            TitlePosition      = OnlyVTitlePosition.Bottom;
            TitleHorzAlignment = TextAlignment.Right;

            VerseFont = new FontDefinition
            {
                FontSize   = MainFont.FontSize * VerseFontSizeFactor,
                FontFamily = MainFont.FontFamily,
                FontColor  = FromHtmlString("#FCBA04"),
                FontStyle  = FontStyles.Normal
            };

            BackgroundImageOpacity = 1.0;

            CultureInfo             = CultureInfo.InvariantCulture;
            FlowDirection           = FlowDirection.LeftToRight;
            AllowAutoFit            = true;
            ShowBreakInVerses       = true;
            UseContinuationEllipses = true;

            TitleDropShadow           = true;
            TitleDropShadowColor      = Colors.Black;
            TitleDropShadowOpacity    = 0.5;
            TitleDropShadowBlurRadius = 10;
            TitleDropShadowDepth      = 10;

            BodyDropShadow           = true;
            BodyDropShadowColor      = Colors.Black;
            BodyDropShadowOpacity    = 0.5;
            BodyDropShadowBlurRadius = 10;
            BodyDropShadowDepth      = 10;
            BodyVerticalAlignment    = OnlyVBodyVerticalAlignment.Middle;

            UseTildeParaSeparator = true;
            TrimPunctuation       = false;
            TrimQuotes            = false;
        }
コード例 #34
0
        private static void ConvertXmlToSub()
        {
            string      filename = ConsolePath("Path to XML file..?");
            Stream      stream   = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlReader   reader   = XmlReader.Create(stream);
            XmlDocument doc      = new XmlDocument();

            doc.Load(reader);
            XmlElement root = doc.DocumentElement;

            reader.Close();
            stream.Close();

            List <FontDefinition> fontlist = new List <FontDefinition>();

            XmlElement fonts       = root.GetElementsByTagName("fonts")[0] as XmlElement;
            string     defaultfont = fonts.Attributes["default"].Value;

            foreach (XmlElement element in fonts.GetElementsByTagName("font"))
            {
                FontDefinition font = new FontDefinition();
                font.ID = element.Attributes["id"].Value;
                foreach (XmlElement sub in element.ChildNodes)
                {
                    switch (sub.Name)
                    {
                    case "scale":
                        font.Scale = new PointF(float.Parse(sub.Attributes["x"].Value), float.Parse(sub.Attributes["y"].Value));
                        break;

                    case "position":
                        font.Position = new PointF(float.Parse(sub.Attributes["x"].Value), float.Parse(sub.Attributes["y"].Value));
                        break;

                    case "angle":
                        font.Angle = float.Parse(sub.Attributes["value"].Value);
                        break;

                    case "colour":
                    case "color":
                        break;

                    case "limit":
                        font.Limit = new PointF(float.Parse(sub.Attributes["x"].Value), float.Parse(sub.Attributes["y"].Value));
                        break;
                    }
                }

                fontlist.Add(font);
            }

            List <Subtitle> subtitles = new List <Subtitle>();

            XmlElement timeline = root.GetElementsByTagName("timeline")[0] as XmlElement;

            foreach (XmlElement element in timeline.GetElementsByTagName("entry"))
            {
                uint frame = 0;
                if (element.HasAttribute("frame"))
                {
                    frame = uint.Parse(element.Attributes["frame"].Value);
                }
                else if (element.HasAttribute("time"))
                {
                    frame = (uint)(double.Parse(element.Attributes["frame"].Value) * 30);                     // FPS? :(
                }
                foreach (XmlElement sub in element.GetElementsByTagName("subtitle"))
                {
                    Subtitle subtitle = new Subtitle();
                    if (sub.HasAttribute("font"))
                    {
                        subtitle.Font = sub.Attributes["font"].Value;
                    }
                    else
                    {
                        subtitle.Font = defaultfont;
                    }

                    subtitle.Frame = frame;
                    subtitle.Value = sub.InnerText;

                    subtitles.Add(subtitle);
                }
            }

            int entrycount = (int)Util.RoundUp(subtitles.Count, 0x20 / 0x08);

            Dictionary <string, ushort> strings = new Dictionary <string, ushort>();
            MemoryStream stringtable            = new MemoryStream();
            EndianReader stringwriter           = new EndianReader(stringtable, Endianness.BigEndian);

            MemoryStream entrytable  = new MemoryStream();
            EndianReader entrywriter = new EndianReader(entrytable, Endianness.BigEndian);

            foreach (Subtitle entry in subtitles)
            {
                WriteSubtitleEntry(fontlist, strings, stringtable, stringwriter, entrywriter, entry);
            }

            for (int i = subtitles.Count; i < entrycount; i++)
            {
                WriteSubtitleEntry(fontlist, strings, stringtable, stringwriter, entrywriter, subtitles.Last());
            }

            stringwriter.PadToMultiple(0x20);

            FileStream   ostream = new FileStream(Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + ".sub"), FileMode.Create, FileAccess.Write, FileShare.None);
            EndianReader writer  = new EndianReader(ostream, Endianness.BigEndian);

            writer.Write((uint)stringtable.Length);
            writer.Write(entrycount);
            writer.Write((uint)fontlist.Count);
            writer.PadTo(0x20);

            stringtable.Position = 0;
            Util.StreamCopy(writer, stringtable);

            entrytable.Position = 0;
            Util.StreamCopy(writer, entrytable);

            foreach (FontDefinition font in fontlist)
            {
                writer.Write(font.Scale.X);
                writer.Write(font.Scale.Y);
                writer.Write(font.Position.X);
                writer.Write(font.Position.Y);
                writer.Write(font.PositionValue);
                writer.Write(font.Angle);
                writer.Write(font.Limit.X);
                writer.Write(font.Limit.Y);
            }

            ostream.Close();
        }
コード例 #35
0
    protected override void Apply(ImageProcessingActionExecuteArgs args)
    {
        Bitmap result = null;
        try
        {
            // Create the result image
            result = new Bitmap(350, 350, CodeCarvings.Piczard.CommonData.DefaultPixelFormat);

            // Set the right image resolution (DPI)
            ImageHelper.SetImageResolution(result, args.ImageProcessingJob.OutputResolution);

            using (Graphics g = Graphics.FromImage(result))
            {
                // Use the max quality
                ImageHelper.SetGraphicsMaxQuality(g);

                if ((args.IsLastAction) && (!args.AppliedImageBackColorValue.HasValue))
                {
                    // Optimization (not mandatory)
                    // This is the last filter action and the ImageBackColor has not been yet applied...
                    // Apply the ImageBackColor now to save RAM & CPU
                    args.ApplyImageBackColor(g);
                }

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    // Important
                    imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

                    // Draw the scaled image
                    Rectangle destinationRectangle = new Rectangle(75, 52, 200, 200);
                    using (Image resizedImage = new FixedCropConstraint(GfxUnit.Pixel, destinationRectangle.Size).GetProcessedImage(args.Image))
                    {
                        g.DrawImage(resizedImage, destinationRectangle, 0, 0, resizedImage.Width, resizedImage.Height, GraphicsUnit.Pixel, imageAttributes);

                        // Draw the reflection
                        destinationRectangle = new Rectangle(75, 252, 200, 98);
                        using (Image flippedImage = ImageTransformation.FlipVertical.GetProcessedImage(resizedImage))
                        {
                            g.DrawImage(flippedImage, destinationRectangle, 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, imageAttributes);
                        }
                    }

                    // Draw the mask
                    destinationRectangle = new Rectangle(0, 0, result.Width, result.Height);
                    using (LoadedImage loadedImage = ImageArchiver.LoadImage("~/repository/filters/MyCustomFilter1Mask.png"))
                    {
                        g.DrawImage(loadedImage.Image, destinationRectangle, 0, 0, loadedImage.Size.Width, loadedImage.Size.Height, GraphicsUnit.Pixel, imageAttributes);
                    }
                }

                // Draw the text
                string text = "Generated by 'MyCustomFilter1' on " + DateTime.Now.ToString();
                FontDefinition fontDefinition = new FontDefinition();
                fontDefinition.Size = 12; //12px
                using (Font font = fontDefinition.GetFont())
                {
                    // Setup the custom parameters
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    using (StringFormat stringFormat = new StringFormat())
                    {
                        SizeF textSize = g.MeasureString(text, font, int.MaxValue, stringFormat);
                        Size pixelTextSize = new Size(Convert.ToInt32(Math.Round(textSize.Width)), Convert.ToInt32(Math.Round(textSize.Height)));

                        // Calculate the text position
                        Point location = new Point((result.Width - pixelTextSize.Width) / 2, result.Height - 14 - pixelTextSize.Height);

                        // Draw the text
                        using (Brush brush = new SolidBrush(ColorTranslator.FromHtml("#5b615d")))
                        {
                            g.DrawString(text, font, brush, location, stringFormat);
                        }
                    }
                }
            }

            // Return the image
            args.Image = result;
        }
        catch
        {
            // An error has occurred...

            // Release the resources
            if (result != null)
            {
                result.Dispose();
                result = null;
            }

            // Re-throw the exception
            throw;
        }
    }
コード例 #36
0
        public FontDefinition ReadFontDefinition(int index)
        {
            FontAsset fontAsset = null;
            Font      font      = null;
            var       value     = m_Values[m_CurrentValueIndex + index];

            switch (value.handle.valueType)
            {
            case StyleValueType.ResourcePath:
            {
                string path = value.sheet.ReadResourcePath(value.handle);
                if (!string.IsNullOrEmpty(path))
                {
                    font = Panel.LoadResource(path, typeof(Font), dpiScaling) as Font;
                    if (font == null)
                    {
                        fontAsset = Panel.LoadResource(path, typeof(FontAsset), dpiScaling) as FontAsset;
                    }
                }

                if (fontAsset == null && font == null)
                {
                    Debug.LogWarning(string.Format("Font not found for path: {0}", path));
                }

                break;
            }

            case StyleValueType.AssetReference:
            {
                font = value.sheet.ReadAssetReference(value.handle) as Font;
                if (font == null)
                {
                    fontAsset = value.sheet.ReadAssetReference(value.handle) as FontAsset;
                }

                break;
            }

            case StyleValueType.Keyword:
            {
                if (value.handle.valueIndex != (int)StyleValueKeyword.None)
                {
                    Debug.LogWarning("Invalid keyword for font " + (StyleValueKeyword)value.handle.valueIndex);
                }

                break;
            }

            default:
                Debug.LogWarning("Invalid value for font " + value.handle.valueType);
                break;
            }

            FontDefinition sfd;

            if (font != null)
            {
                sfd = FontDefinition.FromFont(font);
            }
            else if (fontAsset != null)
            {
                sfd = FontDefinition.FromSDFFont(fontAsset);
            }
            else
            {
                sfd = new FontDefinition();
            }
            return(sfd);
        }