Пример #1
0
        public FormattedTextImpl(string text, string fontFamilyName, double fontSize, FontStyle fontStyle,
                    TextAlignment textAlignment, FontWeight fontWeight, TextWrapping wrapping)
        {
            _text = text ?? string.Empty;

            // Replace 0 characters with zero-width spaces (200B)
            _text = _text.Replace((char)0, (char)0x200B);

            var typeface = TypefaceCache.GetTypeface(fontFamilyName, fontStyle, fontWeight);

            _paint = new SKPaint();

            //currently Skia does not measure properly with Utf8 !!!
            //Paint.TextEncoding = SKTextEncoding.Utf8;
            _paint.TextEncoding = SKTextEncoding.Utf16;
            _paint.IsStroke = false;
            _paint.IsAntialias = true;            
            _paint.LcdRenderText = true;            
            _paint.SubpixelText = true;
            _paint.Typeface = typeface;
            _paint.TextSize = (float)fontSize;
            _paint.TextAlign = textAlignment.ToSKTextAlign();

            _wrapping = wrapping;

            Rebuild();
        }
Пример #2
0
 ///<summary>
 /// Creates a new DrawableFont instance.
 ///</summary>
 ///<param name="family">The font family or the full path to the font file.</param>
 ///<param name="style">The style of the font.</param>
 ///<param name="weight">The weight of the font.</param>
 ///<param name="stretch">The font stretching type.</param>
 public DrawableFont(string family, FontStyleType style, FontWeight weight, FontStretch stretch)
 {
   Family = family;
   Style = style;
   Weight = weight;
   Stretch = stretch;
 }
Пример #3
0
		public Font(string family, float size, FontWeight weight, FontSlant style)
		{
			this.Family = family;
			this.Size = size;
			this.Weight = weight;
			this.Style = style;
		}
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormattedText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            //TODO: Find out why it was null in the first place. Demo project - AvalonStudio
            //https://github.com/VitalElement/AvalonStudio/commit/787fb9396feb74e6ca6bd4e08436269a349df9c6
            text = text ?? "";
            Text = text;
            FontFamilyName = fontFamilyName;
            FontSize = fontSize;
            FontStyle = fontStyle;
            FontWeight = fontWeight;
            TextAlignment = textAlignment;

            var platform = PerspexLocator.Current.GetService<IPlatformRenderInterface>();

            PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Пример #5
0
 public Font(string family, FontStyle style, FontWeight weight, float size)
 {
     Family = family;
     mStyle = style;
     Weight = weight;
     Size = size;
 }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormattedText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            Contract.Requires<ArgumentNullException>(text != null);
            Contract.Requires<ArgumentNullException>(fontFamilyName != null);
            Contract.Requires<ArgumentException>(fontSize > 0);

            Text = text;
            FontFamilyName = fontFamilyName;
            FontSize = fontSize;
            FontStyle = fontStyle;
            FontWeight = fontWeight;
            TextAlignment = textAlignment;

            var platform = PerspexLocator.Current.GetService<IPlatformRenderInterface>();

            if (platform == null)
            {
                throw new Exception("Could not create FormattedText: IPlatformRenderInterface not registered.");
            }

            PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Пример #7
0
 public Typeface(FontFamily fontFamily, FontStyle style, FontWeight weight, FontStretch stretch)
 {
     this.FontFamily = fontFamily;
     this.Style = style;
     this.Weight = weight;
     this.Stretch = stretch;
 }
Пример #8
0
        public FormattedTextImpl(
            Pango.Context context,
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(text != null);
            Layout = new Pango.Layout(context);
            _text = text;
            Layout.SetText(text);
            Layout.FontDescription = new Pango.FontDescription
            {
                Family = fontFamily,
                Size = Pango.Units.FromDouble(CorrectScale(fontSize)),
                Style = (Pango.Style)fontStyle,
                Weight = fontWeight.ToCairo()
            };

            Layout.Alignment = textAlignment.ToCairo();
            Layout.Attributes = new Pango.AttrList();
        }
Пример #9
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            var factory = Locator.Current.GetService<DWrite.Factory>();

            var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize);

            TextLayout = new DWrite.TextLayout(
                factory,
                text ?? string.Empty,
                format,
                float.MaxValue,
                float.MaxValue);

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
Пример #10
0
 public Typeface(FontFamily fontFamily, FontStyle style = FontStyle.Normal, FontWeight weight = FontWeight.Normal, FontStretch stretch = FontStretch.Normal)
 {
     this.FontFamily = fontFamily;
     this.Style = style;
     this.Weight = weight;
     this.Stretch = stretch;
 }
Пример #11
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight,
            TextWrapping wrapping)
        {
            var factory = AvaloniaLocator.Current.GetService<DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize))
            {
                format.WordWrapping = wrapping == TextWrapping.Wrap ? 
                    DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    float.MaxValue,
                    float.MaxValue);
            }

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
Пример #12
0
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            this.Text = text;
            this.FontFamilyName = fontFamilyName;
            this.FontSize = fontSize;
            this.FontStyle = fontStyle;
            this.FontWeight = fontWeight;
            this.TextAlignment = textAlignment;

            var platform = Locator.Current.GetService<IPlatformRenderInterface>();

            this.PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Пример #13
0
 public HtmlFont(FontStyle style, FontVariant variant, FontWeight weight, Unit size, FontFamily family)
 {
     this.style = style;
     this.variant = variant;
     this.family = family;
     this.weight = weight;
     this.size = size;
 }
Пример #14
0
 public override object Create(string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch)
 {
     object o = NSFont.FromFontName (fontName, (float)size);
     o = SetStyle (o, style);
     o = SetWeight (o, weight);
     o = SetStretch (o, stretch);
     return o;
 }
Пример #15
0
    /// <summary>
    /// Initializes a new instance of the <see cref="DrawableFont"/> class.
    /// </summary>
    /// <param name="family">The font family or the full path to the font file.</param>
    /// <param name="style">The style of the font.</param>
    /// <param name="weight">The weight of the font.</param>
    /// <param name="stretch">The font stretching type.</param>
    public DrawableFont(string family, FontStyleType style, FontWeight weight, FontStretch stretch)
    {
      Throw.IfNullOrEmpty(nameof(family), family);

      Family = family;
      Style = style;
      Weight = weight;
      Stretch = stretch;
    }
Пример #16
0
 public static IntPtr GetTypeface(string name, FontStyle style, FontWeight weight)
 {
     Style sstyle = Style.Normal;
     if (style != FontStyle.Normal)
         sstyle |= Style.Italic;
     if(weight>FontWeight.Normal)
     sstyle |= Style.Bold;
     return GetTypeface(name, sstyle);
 }
Пример #17
0
		public override object Create (string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch)
		{
			var t = GetStretchTrait (stretch) | GetStyleTrait (style);
			var f = NSFontManager.SharedFontManager.FontWithFamily (fontName, t, GetWeightValue (weight), (float)size);
			var fd = FontData.FromFont (NSFontManager.SharedFontManager.ConvertFont (f, t));
			fd.Style = style;
			fd.Weight = weight;
			fd.Stretch = stretch;
			return fd;
		}
Пример #18
0
 public IFormattedTextImpl CreateFormattedText(
     string text, 
     string fontFamily, 
     double fontSize, 
     FontStyle fontStyle,
     TextAlignment textAlignment,
     FontWeight fontWeight)
 {
     return new FormattedTextImpl(text, fontFamily, fontSize, fontStyle, textAlignment, fontWeight);
 }
Пример #19
0
 public ScreenSpaceText(string text, Color textClr, string fontFace,
                        FontWeight fontWeight, int fontSize,
                        Vector3 worldPos)
 {
     this.text = text;
     this.textClr = textClr;
     this.fontFace = fontFace;
     this.fontWeight = fontWeight;
     this.fontSize = fontSize;
     this.worldPos = worldPos;
 }
Пример #20
0
 public IFormattedTextImpl CreateFormattedText(
     string text,
     string fontFamilyName,
     double fontSize,
     FontStyle fontStyle,
     TextAlignment textAlignment,
     FontWeight fontWeight,
     TextWrapping wrapping)
 {
     throw new NotImplementedException();
 }
Пример #21
0
		public ParagraphGenerator()
		{
#if WINRT
			FontStyle = FontStyle.Normal;
			FontWeight = FontWeights.Normal; 
#else
			FontStyle = FontStyles.Normal;
			FontWeight = FontWeights.Normal;
#endif

			UseTextSplitting = true; 
		}
 public static FormattedTextImpl Create(string text, string fontFamilyName, double fontSize, FontStyle fontStyle,
     TextAlignment textAlignment, FontWeight fontWeight)
 {
     NativeFormattedText* pShared;
     fixed (void* ptext = text)
     {
         IntPtr handle = MethodTable.Instance.CreateFormattedText(ptext, text.Length,
             TypefaceCache.GetTypeface(fontFamilyName, fontStyle, fontWeight),
             (float) fontSize, textAlignment, &pShared);
         return new FormattedTextImpl(handle, pShared, text);
     }
 }
Пример #23
0
        public ScreenSpaceText(string text, Color textClr, string fontFace,
                               FontWeight fontWeight, int fontSize,
                               Vector3 worldPos, IWorldEntity dependancy)
        {
            this.text = text;
            this.textClr = textClr;
            this.fontFace = fontFace;
            this.fontWeight = fontWeight;
            this.fontSize = fontSize;
            this.worldPos = worldPos;

            Dependancy = dependancy;
        }
Пример #24
0
 /// <summary>
 /// Create a text format object used for text layout.
 /// </summary>
 /// <param name="fontFamilyName">Name of the font family</param>
 /// <param name="fontWeight">Font weight</param>
 /// <param name="fontStyle">Font style</param>
 /// <param name="fontStretch">Font stretch</param>
 /// <param name="fontSize">Logical size of the font in DIP units. A DIP ("device-independent pixel") equals 1/96 inch.</param>
 /// <param name="localeName">Locale name(optional)</param>
 /// TODO understand the meaning of Locale name
 /// <returns> newly created text format object </returns>
 public static TextFormat CreateTextFormat(
     string fontFamilyName,
     FontWeight fontWeight, FontStyle fontStyle, FontStretch fontStretch,
     float fontSize,
     string localeName = "en-us")
 {
     var ptr = Factory.CreateTextFormat(fontFamilyName, IntPtr.Zero,
         fontWeight,
         fontStyle, fontStretch, fontSize,
         localeName);
     var dWriteTextFormat = new TextFormat(ptr);
     return dWriteTextFormat;
 }
Пример #25
0
        public bool RegisterFont(string name, float fontSize, string fontFace = "Arial", FontWeight fontWeight = FontWeight.Normal, FontStyle fontStyle = FontStyle.Normal, FontStretch fontStretch = FontStretch.Normal) {
            if (_fonts.ContainsKey(name)) {
                Console.WriteLine("Duplicate font name: " + name);
                return false;
            }
            try {
                _fonts[name] = new TextBlockRenderer(_sprite, fontFace, fontWeight, fontStyle, fontStretch, fontSize);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return false;
            }

            return true;
        }
Пример #26
0
        public Font this[string family, float size, FontWeight weight = FontWeight.Normal]
        {
            get
            {
                var font = mFonts.FirstOrDefault(f => f.Family == family && Math.Abs(f.Size - size) < 1 && f.Weight == weight);
                if (font != null)
                    return font;

                font = new Font(family, FontStyle.Normal, weight, size);
                font.OnUpdateTarget(mFactory);
                mFonts.Add(font);
                return font;
            }
        }
Пример #27
0
        /// <summary>
        /// Measure the ratio between the width and the height of the text layout.
        /// Returns <see cref="double.NaN"/> if the input does not result in a renderable text.
        /// </summary>
        /// <param name="text">The contents of the layout</param>
        /// <param name="fontHeight">The height of the layout</param>
        /// <param name="fontFamily">The font family of the layout</param>
        /// <param name="fontWeight">The weight of the font used in the layout</param>
        /// <returns>
        /// The ratio between the width and the height of the text layout, i.e. Width/Height. 
        /// <see cref="double.NaN"/> if the input does not result in a renderable text.
        /// </returns>
        public double MeasureWidthToHeightRatio(string text, double fontHeight, string fontFamily, FontWeight fontWeight)
        {
            // Make sure the text is renderable.
            if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(fontFamily) || fontHeight <= 0)
                return double.NaN;

            // Initialize the context to run the calculations.
            using (var font = new Font(new FontFamily(fontFamily), (float)fontHeight, ToFontStyle(fontWeight), GraphicsUnit.Millimeter))
            using (var image = new Bitmap(1, 1))
            using (var graphics = System.Drawing.Graphics.FromImage(image))
            {
                var size = graphics.MeasureString(text, font);
                return size.Width / size.Height;
            }
        }
Пример #28
0
        public GDIFont(string lfFaceName, int lfHeight,
            byte lfPitchAndFamily, byte lfCharSet,
            FontQuality lfQuality, FontWeight lfWeight, bool lfItalic, bool lfStrikeOut, bool lfUnderline,
            byte lfClipPrecision, byte lfOutPrecision,
            int lfEscapement, int lfOrientation,
            int lfWidth, Guid aGuid)
            : base(true, aGuid)
        {
            fFaceName = lfFaceName;
            fHeight = lfHeight;

            fLogFont = new LOGFONT();
            //fLogFont.Init();
            fLogFont.lfCharSet = lfCharSet;
            fLogFont.lfClipPrecision = lfClipPrecision;
            fLogFont.lfEscapement = lfEscapement;
            fLogFont.lfFaceName = lfFaceName;
            fLogFont.lfHeight = lfHeight;
            fLogFont.lfItalic = (byte)(lfItalic ? 1 : 0);
            fLogFont.lfOrientation = lfOrientation;
            fLogFont.lfOutPrecision = lfOutPrecision;
            fLogFont.lfPitchAndFamily = lfPitchAndFamily;
            fLogFont.lfQuality = (byte)lfQuality;
            fLogFont.lfStrikeOut = (byte)(lfStrikeOut ? 1 : 0);
            fLogFont.lfUnderline = (byte)(lfUnderline ? 1 : 0);
            fLogFont.lfWeight = (int)lfWeight;
            fLogFont.lfWidth = lfWidth;

            //fFontHandle = GDI32.CreateFontIndirect(ref fLogFont);
            
            IntPtr fontHandle = GDI32.CreateFontW(
                lfHeight, lfWidth,
                lfEscapement, lfOrientation,
                (int)lfWeight,
                (uint)(lfItalic ? 1 : 0), 
                (uint)(lfUnderline ? 1 : 0), 
                (uint)(lfStrikeOut ? 1 : 0),
                lfCharSet, 
                lfOutPrecision, 
                lfClipPrecision,
                (uint)lfQuality, 
                lfPitchAndFamily, 
                lfFaceName);

            SetHandle(fontHandle);
        }
Пример #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormattedText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <param name="wrapping">The text wrapping mode.</param>
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle = FontStyle.Normal,
            TextAlignment textAlignment = TextAlignment.Left,
            FontWeight fontWeight = FontWeight.Normal,
            TextWrapping wrapping = TextWrapping.Wrap)
        {
            Contract.Requires<ArgumentNullException>(text != null);
            Contract.Requires<ArgumentNullException>(fontFamilyName != null);

            if (fontSize <= 0)
            {
                throw new ArgumentException("FontSize must be greater than 0");
            }

            if (fontWeight <= 0)
            {
                throw new ArgumentException("FontWeight must be greater than 0");
            }

            Text = text;
            FontFamilyName = fontFamilyName;
            FontSize = fontSize;
            FontStyle = fontStyle;
            FontWeight = fontWeight;
            TextAlignment = textAlignment;
            Wrapping = wrapping;

            var platform = AvaloniaLocator.Current.GetService<IPlatformRenderInterface>();

            if (platform == null)
            {
                throw new Exception("Could not create FormattedText: IPlatformRenderInterface not registered.");
            }

            PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight,
                wrapping);
        }
Пример #30
0
        public static SKTypeface GetTypeface(string name, FontStyle style, FontWeight weight)
        {
            SKFontStyleSlant skStyle = SKFontStyleSlant.Upright;

            switch(style)
            {
                case FontStyle.Italic:
                    skStyle = SKFontStyleSlant.Italic;
                    break;

                case FontStyle.Oblique:
                    skStyle = SKFontStyleSlant.Oblique;
                    break;
            }

            return GetTypeface(name, new FontKey((SKFontStyleWeight)weight, skStyle));
        }
 public WpfRichTextBoxWordColoringRule(string text, string textColor, string backgroundColor, FontStyle fontStyle, FontWeight fontWeight)
 {
     this.Text            = text;
     this.FontColor       = textColor;
     this.BackgroundColor = backgroundColor;
     this.Style           = fontStyle;
     this.Weight          = fontWeight;
 }
Пример #32
0
        private void FontStyleBold_Clicked(object sender, RoutedEventArgs e)
        {
            this.boldnes = this.boldnes == FontWeights.Normal ? FontWeights.Bold : FontWeights.Normal;

            this.uxHtmlText.Selection.ApplyPropertyValue(TextElement.FontWeightProperty, this.boldnes);
        }
Пример #33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FontFace"/> class.
        /// </summary>
        /// <param name="stream">A stream pointing to the font file.</param>
        /// <remarks>
        /// All relevant font data is loaded into memory and retained by the FontFace object.
        /// Once the constructor finishes you are free to close the stream.
        /// </remarks>
        public FontFace(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream", "Empty stream for FontFace!");
            }

            // read the face header and table records
            using (var reader = new DataReader(stream))
            {
                var tables = SfntTables.ReadFaceHeader(reader);

                // read head and maxp tables for font metadata and limits
                FaceHeader head;
                SfntTables.ReadHead(reader, tables, out head);
                SfntTables.ReadMaxp(reader, tables, ref head);
                unitsPerEm   = head.UnitsPerEm;
                integerPpems = (head.Flags & HeadFlags.IntegerPpem) != 0;

                // horizontal metrics header and data
                SfntTables.SeekToTable(reader, tables, FourCC.Hhea, required: true);
                var hMetricsHeader = SfntTables.ReadMetricsHeader(reader);
                SfntTables.SeekToTable(reader, tables, FourCC.Hmtx, required: true);
                hmetrics = SfntTables.ReadMetricsTable(reader, head.GlyphCount, hMetricsHeader.MetricCount);

                // font might optionally have vertical metrics
                if (SfntTables.SeekToTable(reader, tables, FourCC.Vhea))
                {
                    var vMetricsHeader = SfntTables.ReadMetricsHeader(reader);

                    SfntTables.SeekToTable(reader, tables, FourCC.Vmtx, required: true);
                    vmetrics = SfntTables.ReadMetricsTable(reader, head.GlyphCount, vMetricsHeader.MetricCount);
                }

                // OS/2 table has even more metrics
                var os2Data = SfntTables.ReadOS2(reader, tables);
                xHeight   = os2Data.XHeight;
                capHeight = os2Data.CapHeight;
                Weight    = os2Data.Weight;
                Stretch   = os2Data.Stretch;
                Style     = os2Data.Style;

                // optional PostScript table has random junk in it
                SfntTables.ReadPost(reader, tables, ref head);
                IsFixedWidth = head.IsFixedPitch;

                // read character-to-glyph mapping tables and kerning table
                charMap   = CharacterMap.ReadCmap(reader, tables);
                kernTable = KerningTable.ReadKern(reader, tables);

                // name data
                var names = SfntTables.ReadNames(reader, tables);
                Family      = names.TypographicFamilyName ?? names.FamilyName;
                Subfamily   = names.TypographicSubfamilyName ?? names.SubfamilyName;
                FullName    = names.FullName;
                UniqueID    = names.UniqueID;
                Version     = names.Version;
                Description = names.Description;

                // load glyphs if we have them
                if (SfntTables.SeekToTable(reader, tables, FourCC.Glyf))
                {
                    unsafe
                    {
                        // read in the loca table, which tells us the byte offset of each glyph
                        var loca = stackalloc uint[head.GlyphCount];
                        SfntTables.ReadLoca(reader, tables, head.IndexFormat, loca, head.GlyphCount);

                        // we need to know the length of the glyf table because of some weirdness in the loca table:
                        // if a glyph is "missing" (like a space character), then its loca[n] entry is equal to loca[n+1]
                        // if the last glyph in the set is missing, then loca[n] == glyf table length
                        SfntTables.SeekToTable(reader, tables, FourCC.Glyf);
                        var glyfOffset = reader.Position;
                        var glyfLength = tables[SfntTables.FindTable(tables, FourCC.Glyf)].Length;

                        // read in all glyphs
                        glyphs = new BaseGlyph[head.GlyphCount];
                        for (int i = 0; i < glyphs.Length; i++)
                        {
                            SfntTables.ReadGlyph(reader, i, 0, glyphs, glyfOffset, glyfLength, loca);
                        }
                    }
                }

                // embedded bitmaps
                SbitTable.Read(reader, tables);

                // metrics calculations: if the UseTypographicMetrics flag is set, then
                // we should use the sTypo*** data for line height calculation
                if (os2Data.UseTypographicMetrics)
                {
                    // include the line gap in the ascent so that
                    // white space is distributed above the line
                    cellAscent  = os2Data.TypographicAscender + os2Data.TypographicLineGap;
                    cellDescent = -os2Data.TypographicDescender;
                    lineHeight  = os2Data.TypographicAscender + os2Data.TypographicLineGap - os2Data.TypographicDescender;
                }
                else
                {
                    // otherwise, we need to guess at whether hhea data or os/2 data has better line spacing
                    // this is the recommended procedure based on the OS/2 spec extra notes
                    cellAscent  = os2Data.WinAscent;
                    cellDescent = Math.Abs(os2Data.WinDescent);
                    lineHeight  = Math.Max(
                        Math.Max(0, hMetricsHeader.LineGap) + hMetricsHeader.Ascender + Math.Abs(hMetricsHeader.Descender),
                        cellAscent + cellDescent
                        );
                }

                // give sane defaults for underline and strikeout data if missing
                underlineSize = head.UnderlineThickness != 0 ?
                                head.UnderlineThickness : (head.UnitsPerEm + 7) / 14;
                underlinePosition = head.UnderlinePosition != 0 ?
                                    head.UnderlinePosition : -((head.UnitsPerEm + 5) / 10);
                strikeoutSize = os2Data.StrikeoutSize != 0 ?
                                os2Data.StrikeoutSize : underlineSize;
                strikeoutPosition = os2Data.StrikeoutPosition != 0 ?
                                    os2Data.StrikeoutPosition : head.UnitsPerEm / 3;

                // create some vertical metrics in case we haven't loaded any
                verticalSynthesized = new MetricsEntry
                {
                    FrontSideBearing = os2Data.TypographicAscender,
                    Advance          = os2Data.TypographicAscender - os2Data.TypographicDescender
                };

                // read in global font program data
                controlValueTable = SfntTables.ReadCvt(reader, tables);
                prepProgram       = SfntTables.ReadProgram(reader, tables, FourCC.Prep);
                interpreter       = new Interpreter(
                    head.MaxStackSize,
                    head.MaxStorageLocations,
                    head.MaxFunctionDefs,
                    head.MaxInstructionDefs,
                    head.MaxTwilightPoints
                    );

                // the fpgm table optionally contains a program to run at initialization time
                var fpgm = SfntTables.ReadProgram(reader, tables, FourCC.Fpgm);
                if (fpgm != null)
                {
                    interpreter.InitializeFunctionDefs(fpgm);
                }
            }

            Id = Interlocked.Increment(ref currentId);
        }
        public override void RenderTextRun(SvgTextContentElement element, ref Point ctp,
                                           string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            double emSize         = GetComputedFontSize(element);
            var    fontFamilyInfo = GetTextFontFamilyInfo(element);

            WpfTextStringFormat stringFormat = GetTextStringFormat(element);

            if (fontFamilyInfo.FontFamilyType == WpfFontFamilyType.Svg)
            {
                WpfTextTuple textInfo = new WpfTextTuple(fontFamilyInfo, emSize, stringFormat, element);
                this.RenderTextRun(textInfo, ref ctp, text, rotate, placement);
                return;
            }

            FontFamily  fontFamily  = fontFamilyInfo.Family;
            FontStyle   fontStyle   = fontFamilyInfo.Style;
            FontWeight  fontWeight  = fontFamilyInfo.Weight;
            FontStretch fontStretch = fontFamilyInfo.Stretch;

            // Fix the use of Postscript fonts...
            WpfFontFamilyVisitor fontFamilyVisitor = _context.FontFamilyVisitor;

            if (!string.IsNullOrWhiteSpace(_actualFontName) && fontFamilyVisitor != null)
            {
                WpfFontFamilyInfo familyInfo = fontFamilyVisitor.Visit(_actualFontName,
                                                                       fontFamilyInfo, _context);
                if (familyInfo != null && !familyInfo.IsEmpty)
                {
                    fontFamily  = familyInfo.Family;
                    fontWeight  = familyInfo.Weight;
                    fontStyle   = familyInfo.Style;
                    fontStretch = familyInfo.Stretch;
                }
            }

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            bool isForcedPathMode = false;

            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            else
            {
                // WPF gradient fill does not work well on text, use geometry to render it
                isForcedPathMode = (fillPaint.FillType == WpfFillType.Gradient);
            }
            if (textPen != null)
            {
                textPen.LineJoin = PenLineJoin.Round; // Better for text rendering
                isForcedPathMode = true;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);

            if (textDecors == null)
            {
                SvgTextBaseElement textElement = element.ParentNode as SvgTextBaseElement;

                if (textElement != null)
                {
                    textDecors = GetTextDecoration(textElement);
                }
            }

            TextAlignment alignment = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            var typeFace = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            if (textPositions != null && textPositions.Count != 0)
            {
                if (textPositions.Count == text.Trim().Length) //TODO: Best way to handle this...
                {
                    text = text.Trim();
                }
            }

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                double spacing = Convert.ToDouble(letterSpacing);

                int startSpaces = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (char.IsWhiteSpace(text[i]))
                    {
                        startSpaces++;
                    }
                    else
                    {
                        break;
                    }
                }

                int j = 0;

                string inputText = string.Empty;
                for (int i = 0; i < text.Length; i++)
                {
                    // Avoid rendering only spaces at the start of text run...
                    if (i == 0 && startSpaces != 0)
                    {
                        inputText = text.Substring(0, startSpaces + 1);
                        i        += startSpaces;
                    }
                    else
                    {
                        inputText = new string(text[i], 1);
                    }

                    FormattedText formattedText = new FormattedText(inputText, _context.CultureInfo,
                                                                    stringFormat.Direction, typeFace, emSize, textBrush);

                    if (this.IsMeasuring)
                    {
                        this.AddTextWidth(ctp, formattedText.WidthIncludingTrailingWhitespace);
                        continue;
                    }

                    formattedText.Trimming      = stringFormat.Trimming;
                    formattedText.TextAlignment = stringFormat.Alignment;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        formattedText.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && j < textPosCount)
                    {
                        textPosition = textPositions[j];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = formattedText.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(ctp.X, ctp.Y - yCorrection);

                    if (isForcedPathMode || _context.TextAsGeometry)
                    {
                        Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                        if (textGeometry != null && !textGeometry.IsEmpty())
                        {
                            _drawContext.DrawGeometry(textBrush, textPen,
                                                      ExtractTextPathGeometry(textGeometry));

                            this.IsTextPath = true;
                        }
                        else
                        {
                            _drawContext.DrawText(formattedText, textPoint);
                        }
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                    j++;
                }
            }
            else
            {
                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
                                                                stringFormat.Direction, typeFace, emSize, textBrush);

                if (this.IsMeasuring)
                {
                    this.AddTextWidth(ctp, formattedText.WidthIncludingTrailingWhitespace);
                    return;
                }

                var textContext = this.TextContext;
                if (textContext != null && textContext.IsPositionChanged(element) == false)
                {
                    if (alignment == TextAlignment.Center && this.TextWidth > 0)
                    {
                        alignment = TextAlignment.Left;
                    }
                }

                formattedText.TextAlignment = alignment;
                formattedText.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    formattedText.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = formattedText.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                if (isForcedPathMode || _context.TextAsGeometry)
                {
                    Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }
                }
                else
                {
                    _drawContext.DrawText(formattedText, textPoint);
                }

                //float bboxWidth = (float)formattedText.Width;
                double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Пример #35
0
 public void SelectFontFace(string family, FontSlant slant, FontWeight weight)
 {
     NativeMethods.cairo_select_font_face(state, family, slant, weight);
 }
Пример #36
0
 internal static UIFont TryGetFont(nfloat size, FontWeight fontWeight, FontStyle fontStyle, FontFamily requestedFamily, float?preferredBodyFontSize = null)
 {
     return(_tryGetFont(size, fontWeight, fontStyle, requestedFamily, preferredBodyFontSize ?? DefaultPreferredBodyFontSize));
 }
        internal GlyphTypeface MapGlyphTypeface(
            FontStyle style,
            FontWeight weight,
            FontStretch stretch,
            CharacterBufferRange charString,
            CultureInfo digitCulture,
            ref int advance,
            ref int nextValid
            )
        {
            int smallestInvalid = charString.Length;

            // Add all the cached font faces to a priority queue.
            MatchingStyle targetStyle = new MatchingStyle(style, weight, stretch);

            LegacyPriorityQueue <MatchingFace> queue = new LegacyPriorityQueue <MatchingFace>(
                checked ((int)_family.Count),
                new MatchingFaceComparer(targetStyle));

            foreach (Text.TextInterface.Font face in _family)
            {
                queue.Push(new MatchingFace(face));
            }

            // Remember the best style match.
            MS.Internal.Text.TextInterface.Font bestStyleTypeface = null;

            // Iterate in priority order.
            for (; queue.Count != 0; queue.Pop())
            {
                int invalid = 0;
                MS.Internal.Text.TextInterface.Font font = queue.Top.FontFace;
                int valid = MapCharacters(font, charString, digitCulture, ref invalid);
                if (valid > 0)
                {
                    if (smallestInvalid > 0 && smallestInvalid < valid)
                    {
                        // advance only to smallestInvalid because there's a better match after that
                        advance   = smallestInvalid;
                        nextValid = 0;
                    }
                    else
                    {
                        advance   = valid;
                        nextValid = invalid;
                    }

                    return(new GlyphTypeface(font));
                }
                else
                {
                    if (invalid < smallestInvalid)
                    {
                        // keep track of the current shortest length of invalid characters,
                        smallestInvalid = invalid;
                    }

                    if (bestStyleTypeface == null)
                    {
                        bestStyleTypeface = font;
                    }
                }
            }

            // no face can map the specified character string,
            // fall back to the closest style match
            advance   = 0;
            nextValid = smallestInvalid;
            Debug.Assert(bestStyleTypeface != null);
            return(new GlyphTypeface(bestStyleTypeface));
        }
Пример #38
0
 public static bool Equals(this FontWeight fw1, FontWeight fw2)
 {
     return(fw1.Weight == fw2.Weight);
 }
Пример #39
0
        int IComparable.CompareTo(object obj)
        {
            TypefaceListItem item = obj as TypefaceListItem;

            if (item == null)
            {
                return(-1);
            }

            // Sort all simulated faces after all non-simulated faces.
            if (_simulated != item._simulated)
            {
                return(_simulated ? 1 : -1);
            }

            // If weight differs then sort based on weight (lightest first).
            int difference = FontWeight.ToOpenTypeWeight() - item.FontWeight.ToOpenTypeWeight();

            if (difference != 0)
            {
                return(difference > 0 ? 1 : -1);
            }

            // If style differs then sort based on style (Normal, Italic, then Oblique).
            FontStyle thisStyle  = FontStyle;
            FontStyle otherStyle = item.FontStyle;

            if (thisStyle != otherStyle)
            {
                if (thisStyle == FontStyles.Normal)
                {
                    // This item is normal style and should come first.
                    return(-1);
                }
                else if (otherStyle == FontStyles.Normal)
                {
                    // The other item is normal style and should come first.
                    return(1);
                }
                else
                {
                    // Neither is normal so sort italic before oblique.
                    return((thisStyle == FontStyles.Italic) ? -1 : 1);
                }
            }

            // If stretch differs then sort based on stretch (Normal first, then numerically).
            FontStretch thisStretch  = FontStretch;
            FontStretch otherStretch = item.FontStretch;

            if (thisStretch != otherStretch)
            {
                if (thisStretch == FontStretches.Normal)
                {
                    // This item is normal stretch and should come first.
                    return(-1);
                }
                else if (otherStretch == FontStretches.Normal)
                {
                    // The other item is normal stretch and should come first.
                    return(1);
                }
                else
                {
                    // Neither is normal so sort numerically.
                    return(thisStretch.ToOpenTypeStretch() < otherStretch.ToOpenTypeStretch() ? -1 : 0);
                }
            }

            // They're the same.
            return(0);
        }
Пример #40
0
 internal override void Reset()
 {
     _weight = _weights[Keywords.Normal];
 }
Пример #41
0
        /// <summary>
        /// Adds the font.
        /// </summary>
        /// <param name="family">The family.</param>
        /// <param name="size">The size.</param>
        /// <param name="style">The style.</param>
        /// <param name="weight">The weight.</param>
        /// <param name="method">The method.</param>
        public void AddFont(FontFamily family, double size, FontStyle style, FontWeight weight, CodeMemberMethod method)
        {
            FontInfo info = new FontInfo(family, size, style, weight);

            fonts[info.GetHashCode()] = info;
        }
Пример #42
0
        public bool RegisterFont(string name, float fontSize, string fontFace = "Arial", FontWeight fontWeight = FontWeight.Normal, FontStyle fontStyle = FontStyle.Normal, FontStretch fontStretch = FontStretch.Normal)
        {
            if (_fonts.ContainsKey(name))
            {
                Console.WriteLine("Duplicate font name: " + name);
                return(false);
            }
            try {
                _fonts[name] = new TextBlockRenderer(_sprite, fontFace, fontWeight, fontStyle, fontStretch, fontSize);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return(false);
            }

            return(true);
        }
Пример #43
0
 public D2DSpriteTextformat CreateTextformat(string fontFamiry, int size = 15, FontWeight weight                 = FontWeight.Normal,
                                             FontStyle style             = FontStyle.Normal, FontStretch stretch = FontStretch.Normal, string locale = "ja-jp")
 {
     return(new D2DSpriteTextformat(this, fontFamiry, size, weight, style, stretch, locale));
 }
Пример #44
0
 protected override void OnFontWeightChanged(FontWeight oldValue, FontWeight newValue)
 {
     base.OnFontWeightChanged(oldValue, newValue);
     UpdateFontPartial();
 }
 /// <summary>
 /// Look up device font for the typeface.
 /// </summary>
 IDeviceFont IFontFamily.GetDeviceFont(FontStyle style, FontWeight weight, FontStretch stretch)
 {
     return(null);
 }
Пример #46
0
 public void FontFace(string family, FontSlant slant, FontWeight weight)
 {
     SelectFontFace(family, slant, weight);
 }
 public WpfRichTextBoxWordColoringRule(string text, string textColor, string backgroundColor, FontStyle fontStyle, FontWeight fontWeight)
 {
     Text            = text;
     FontColor       = textColor;
     BackgroundColor = backgroundColor;
     Style           = fontStyle;
     Weight          = fontWeight;
 }
Пример #48
0
 /// <summary>
 /// set HeaderFontWeight
 /// </summary>
 /// <param name="element"></param>
 /// <param name="value"></param>
 public static void SetHeaderFontWeight(IControl element, FontWeight value)
 {
     element.SetValue(HeaderFontWeightProperty, value);
 }
Пример #49
0
        /// <summary>
        /// Measures the provided text with the specified parameters and returns it's size when drawn in WPF application.
        /// </summary>
        /// <param name="text">The text to measure.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <param name="fontStretch">The font stretch.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="visual">The visual target object where this text will be drawn. Used for getting the DPI information. If not provided, it will use the main window of the current application.</param>
        public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize, Visual visual = null)
        {
            if (visual == null)
            {
                visual = Application.Current.MainWindow;
            }
            if (visual == null)
            {
                throw new ArgumentNullException(nameof(visual));
            }
            DpiScale dpiScale      = VisualTreeHelper.GetDpi(visual);
            var      formattedText = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(fontFamily, fontStyle, fontWeight, fontStretch), fontSize, Brushes.Black, dpiScale.PixelsPerDip);

            return(new Size(formattedText.Width, formattedText.Height));
        }
Пример #50
0
 public ListBoxLogMessageString(string message, System.Windows.Media.Brush colore, FontWeight fontWeight, int fontSize)
 {
     Message      = message;
     MessageColor = colore;
     FontWeight   = fontWeight;
     FontSize     = fontSize;
 }
Пример #51
0
        public bool TryMatchCharacter(int codepoint, FontStyle fontStyle,
                                      FontWeight fontWeight,
                                      FontFamily fontFamily, CultureInfo culture, out Typeface fontKey)
        {
            SKFontStyle skFontStyle;

            switch (fontWeight)
            {
            case FontWeight.Normal when fontStyle == FontStyle.Normal:
                skFontStyle = SKFontStyle.Normal;
                break;

            case FontWeight.Normal when fontStyle == FontStyle.Italic:
                skFontStyle = SKFontStyle.Italic;
                break;

            case FontWeight.Bold when fontStyle == FontStyle.Normal:
                skFontStyle = SKFontStyle.Bold;
                break;

            case FontWeight.Bold when fontStyle == FontStyle.Italic:
                skFontStyle = SKFontStyle.BoldItalic;
                break;

            default:
                skFontStyle = new SKFontStyle((SKFontStyleWeight)fontWeight, SKFontStyleWidth.Normal, (SKFontStyleSlant)fontStyle);
                break;
            }

            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }

            if (t_languageTagBuffer == null)
            {
                t_languageTagBuffer = new string[2];
            }

            t_languageTagBuffer[0] = culture.TwoLetterISOLanguageName;
            t_languageTagBuffer[1] = culture.ThreeLetterISOLanguageName;

            if (fontFamily != null && fontFamily.FamilyNames.HasFallbacks)
            {
                var familyNames = fontFamily.FamilyNames;

                for (var i = 1; i < familyNames.Count; i++)
                {
                    var skTypeface =
                        _skFontManager.MatchCharacter(familyNames[i], skFontStyle, t_languageTagBuffer, codepoint);

                    if (skTypeface == null)
                    {
                        continue;
                    }

                    fontKey = new Typeface(skTypeface.FamilyName, fontStyle, fontWeight);

                    return(true);
                }
            }
            else
            {
                var skTypeface = _skFontManager.MatchCharacter(null, skFontStyle, t_languageTagBuffer, codepoint);

                if (skTypeface != null)
                {
                    fontKey = new Typeface(skTypeface.FamilyName, fontStyle, fontWeight);

                    return(true);
                }
            }

            fontKey = default;

            return(false);
        }
Пример #52
0
 private void SetFontWeight(FontWeight weight)
 {
     BoldButton.IsChecked = weight == FontWeights.Bold;
 }
Пример #53
0
 private static UIFont ApplyWeightAndStyle(UIFont font, nfloat size, FontWeight fontWeight, FontStyle fontStyle)
 {
     font = ApplyWeight(font, size, fontWeight);
     font = ApplyStyle(font, size, fontStyle);
     return(font);
 }
Пример #54
0
 partial void OnFontWeightChangedPartial(FontWeight oldValue, FontWeight newValue);
Пример #55
0
        protected WpfFontFamilyInfo GetTextFontFamilyInfo(SvgTextContentElement element)
        {
            _actualFontName = null;

            string fontFamily = element.GetPropertyValue("font-family");

            string[] fontNames = fontNames = fontFamily.Split(new char[1] {
                ','
            });

            FontStyle   fontStyle   = GetTextFontStyle(element);
            FontWeight  fontWeight  = GetTextFontWeight(element);
            FontStretch fontStretch = GetTextFontStretch(element);

            var comparer = StringComparison.OrdinalIgnoreCase;

            var docElement = element.OwnerDocument;

            ISet <string> svgFontFamilies = docElement.SvgFontFamilies;
            IDictionary <string, string> styledFontIds = docElement.StyledFontIds;

            IList <string> svgFontNames = null;

            if (svgFontFamilies != null && svgFontFamilies.Count != 0)
            {
                svgFontNames = new List <string>();
            }
            var systemFontFamilies = Fonts.SystemFontFamilies;

            FontFamily family = null;

            WpfFontFamilyType familyType = WpfFontFamilyType.None;

            foreach (string fn in fontNames)
            {
                try
                {
                    string fontName = fn.Trim(new char[] { ' ', '\'', '"' });
                    if (svgFontFamilies != null && svgFontFamilies.Count != 0)
                    {
                        if (svgFontFamilies.Contains(fontName))
                        {
                            svgFontNames.Add(fontName);
                            continue;
                        }
                        else if (styledFontIds.ContainsKey(fontName))
                        {
                            string mappedFontName = styledFontIds[fontName];
                            if (svgFontFamilies.Contains(mappedFontName))
                            {
                                svgFontNames.Add(mappedFontName);
                                continue;
                            }
                        }
                    }

                    if (string.Equals(fontName, "serif", comparer))
                    {
                        family     = WpfDrawingSettings.GenericSerif;
                        familyType = WpfFontFamilyType.Generic;
                    }
                    else if (string.Equals(fontName, "sans-serif", comparer))
                    {
                        family     = WpfDrawingSettings.GenericSansSerif;
                        familyType = WpfFontFamilyType.Generic;
                    }
                    else if (string.Equals(fontName, "monospace", comparer))
                    {
                        family     = WpfDrawingSettings.GenericMonospace;
                        familyType = WpfFontFamilyType.Generic;
                    }
                    else if (styledFontIds.ContainsKey(fontName))
                    {
                        string mappedFontName = styledFontIds[fontName];
                        var    funcFamily     = new Func <FontFamily, bool>(ff => string.Equals(ff.Source, mappedFontName, comparer));
                        family = systemFontFamilies.FirstOrDefault(funcFamily);
                        if (family != null)
                        {
                            _actualFontName = mappedFontName;
                            familyType      = WpfFontFamilyType.System;
                        }
                    }
                    else
                    {
                        string normalizedFontName;
                        var    funcFamily = new Func <FontFamily, bool>(ff => string.Equals(ff.Source, fontName, comparer));
                        family = systemFontFamilies.FirstOrDefault(funcFamily);
                        if (family != null)
                        {
                            _actualFontName = fontName;
                            familyType      = WpfFontFamilyType.System;
                        }
                        else if (fontName.IndexOf('-') > 0)
                        {
                            normalizedFontName = fontName.Replace("-", " ");
                            funcFamily         = new Func <FontFamily, bool>(ff => string.Equals(ff.Source,
                                                                                                 normalizedFontName, comparer));
                            family = systemFontFamilies.FirstOrDefault(funcFamily);
                            if (family != null)
                            {
                                _actualFontName = normalizedFontName;
                                familyType      = WpfFontFamilyType.System;
                            }
                        }
                        else if (SplitByCaps(fontName, out normalizedFontName))
                        {
                            funcFamily = new Func <FontFamily, bool>(ff => string.Equals(ff.Source,
                                                                                         normalizedFontName, comparer));
                            family = systemFontFamilies.FirstOrDefault(funcFamily);
                            if (family != null)
                            {
                                _actualFontName = normalizedFontName;
                                familyType      = WpfFontFamilyType.System;
                            }
                        }
                    }

                    if (family != null)
                    {
                        return(new WpfFontFamilyInfo(familyType, _actualFontName, family,
                                                     fontWeight, fontStyle, fontStretch));
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }

            // If set, use the SVG-Font...
            if (svgFontNames != null && svgFontNames.Count != 0)
            {
                IList <SvgFontElement> svgFonts = docElement.GetFonts(svgFontNames);
                if (svgFonts != null && svgFonts.Count != 0)
                {
                    string fontVariant = element.GetPropertyValue("font-variant");

                    // For a single match...
                    if (svgFonts.Count == 1)
                    {
                        var fontFamilyInfo = new WpfFontFamilyInfo(svgFonts[0].FontFamily, svgFonts[0],
                                                                   fontWeight, fontStyle, fontStretch);

                        fontFamilyInfo.Variant = fontVariant;
                        return(fontFamilyInfo);
                    }

                    // For multiple matches, we will test the variants...
                    if (string.IsNullOrWhiteSpace(fontVariant))
                    {
                        // Not found, return the first match...
                        var fontFamilyInfo = new WpfFontFamilyInfo(svgFonts[0].FontFamily, svgFonts[0],
                                                                   fontWeight, fontStyle, fontStretch);

                        fontFamilyInfo.Variant = fontVariant;
                        return(fontFamilyInfo);
                    }

                    foreach (var svgFont in svgFonts)
                    {
                        var fontFace = svgFont.FontFace;
                        if (fontFace == null)
                        {
                            continue;
                        }
                        if (fontVariant.Equals(fontFace.FontVariant, comparer))
                        {
                            var fontFamilyInfo = new WpfFontFamilyInfo(svgFont.FontFamily, svgFont,
                                                                       fontWeight, fontStyle, fontStretch);

                            fontFamilyInfo.Variant = fontVariant;
                            return(fontFamilyInfo);
                        }
                    }

                    // If the variant is not found, return the first match...
                    {
                        var fontFamilyInfo = new WpfFontFamilyInfo(svgFonts[0].FontFamily, svgFonts[0],
                                                                   fontWeight, fontStyle, fontStretch);

                        fontFamilyInfo.Variant = fontVariant;
                        return(fontFamilyInfo);
                    }
                }
            }

            // No known font-family was found => default to "Arial Unicode MS"
            return(new WpfFontFamilyInfo(familyType, _actualFontName,
                                         WpfDrawingSettings.DefaultFontFamily, fontWeight, fontStyle, fontStretch));
        }
Пример #56
0
 public ListBoxLogMessageString(string message, System.Windows.Media.Brush colore, FontWeight fontWeight)
 {
     Message      = message;
     MessageColor = colore;
     FontWeight   = fontWeight;
     FontSize     = DEFAULD_FONT_SIZE;
 }
Пример #57
0
 protected virtual void OnFontWeightChanged(FontWeight oldValue, FontWeight newValue)
 {
     OnFontWeightChangedPartial(oldValue, newValue);
 }
Пример #58
0
 /// <summary>
 /// Applies the DrawableFont operation to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="family">The font family or the full path to the font file.</param>
 /// <param name="style">The style of the font.</param>
 /// <param name="weight">The weight of the font.</param>
 /// <param name="stretch">The font stretching type.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public IDrawables <QuantumType> Font(string family, FontStyleType style, FontWeight weight, FontStretch stretch)
 {
     _drawables.Add(new DrawableFont(family, style, weight, stretch));
     return(this);
 }
        private void RenderTextRun(WpfTextTuple textInfo, ref Point ctp,
                                   string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            WpfFontFamilyInfo     familyInfo   = textInfo.Item1;
            double                emSize       = textInfo.Item2;
            WpfTextStringFormat   stringFormat = textInfo.Item3;
            SvgTextContentElement element      = textInfo.Item4;

            FontFamily  fontFamily  = familyInfo.Family;
            FontWeight  fontWeight  = familyInfo.Weight;
            FontStyle   fontStyle   = familyInfo.Style;
            FontStretch fontStretch = familyInfo.Stretch;

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            if (textPen != null)
            {
                textPen.LineJoin   = PenLineJoin.Miter; // Better for text rendering
                textPen.MiterLimit = 1;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);

            if (textDecors == null)
            {
                SvgTextBaseElement textElement = element.ParentNode as SvgTextBaseElement;

                if (textElement != null)
                {
                    textDecors = GetTextDecoration(textElement);
                }
            }

            TextAlignment alignment = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            WpfTextBuilder textBuilder = WpfTextBuilder.Create(familyInfo, this.TextCulture, emSize);

            this.IsTextPath = true;

            if (textPositions != null && textPositions.Count != 0)
            {
                if (textPositions.Count == text.Trim().Length) //TODO: Best way to handle this...
                {
                    text = text.Trim();
                }
            }

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                double spacing = Convert.ToDouble(letterSpacing);

                int startSpaces = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (char.IsWhiteSpace(text[i]))
                    {
                        startSpaces++;
                    }
                    else
                    {
                        break;
                    }
                }

                int j = 0;

                string inputText = string.Empty;
                for (int i = 0; i < text.Length; i++)
                {
                    // Avoid rendering only spaces at the start of text run...
                    if (i == 0 && startSpaces != 0)
                    {
                        inputText = text.Substring(0, startSpaces + 1);
                        i        += startSpaces;
                    }
                    else
                    {
                        inputText = new string(text[i], 1);
                    }

                    if (this.IsMeasuring)
                    {
                        var textSize = textBuilder.MeasureText(element, inputText);
                        this.AddTextWidth(ctp, textSize.Width);
                        continue;
                    }

                    textBuilder.Trimming      = stringFormat.Trimming;
                    textBuilder.TextAlignment = stringFormat.Alignment;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        textBuilder.TextDecorations = textDecors;
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && j < textPosCount)
                    {
                        textPosition = textPositions[j];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = textBuilder.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(ctp.X, ctp.Y - yCorrection);

                    Geometry textGeometry = textBuilder.Build(element, inputText, textPoint.X, textPoint.Y);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
//                        _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));
                        _drawContext.DrawGeometry(textBrush, textPen, textGeometry);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = textGeometry.Bounds.Width;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                    j++;
                }
            }
            else
            {
                if (this.IsMeasuring)
                {
                    var textSize = textBuilder.MeasureText(element, text);
                    this.AddTextWidth(ctp, textSize.Width);
                    return;
                }

                var textContext = this.TextContext;
                if (textContext != null && textContext.IsPositionChanged(element) == false)
                {
                    if (alignment == TextAlignment.Center && this.TextWidth > 0)
                    {
                        alignment = TextAlignment.Left;
                    }
                }

                textBuilder.TextAlignment = alignment;
                textBuilder.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    textBuilder.TextDecorations = textDecors;
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = textBuilder.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                Geometry textGeometry = textBuilder.Build(element, text, textPoint.X, textPoint.Y);
                if (textGeometry != null && !textGeometry.IsEmpty())
                {
//                    _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));
                    _drawContext.DrawGeometry(textBrush, textPen, textGeometry);
                }

                //float bboxWidth = (float)formattedText.Width;
                //                double bboxWidth = textGeometry.Bounds.Width;
                double bboxWidth = textBuilder.Width;

                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Пример #60
0
        private void CreatePivotTable(StackPanel stackPanel, int[] arraySum, DataRow row = null)
        {
            if (stackPanel.Name == "StackPanelDep")
            {
                ButtonAdd.Visibility = Visibility.Visible;
            }

            Border stackPanelRowBorder = new Border
            {
                BorderBrush     = Brushes.CadetBlue,
                BorderThickness = new Thickness(0.3)
            };

            StackPanel stackPanelRow = new StackPanel()
            {
                Orientation = Orientation.Horizontal,
                Margin      = new Thickness(0, 2, 0, 0),
            };

            stackPanelRowBorder.Child = stackPanelRow;

            //Кол-во колонок определенных в шапке таблице в xaml
            int numCols = ((StackPanel)stackPanel.Children[0]).Children.Count;

            //Перебор колонок
            for (int j = 0; j < numCols; j++)
            {
                string     txt;
                FontWeight fontWeight;

                //Если в вызове нет DataRow то выводим сумму и делаем ее жирной
                if (row == null)
                {
                    //Вывожу Итого вместо первого значения массива
                    txt = j == 0 ? "Итого" : arraySum[j].ToString();

                    //Для последней колонки и для StackPanelDep нахожу отношение кол-ва баллов к норме баллов
                    if (j == numCols - 1 && arraySum[1] != 0 && stackPanel.Name == "StackPanelDep")
                    {
                        txt = (arraySum[2] / arraySum[1] * 100).ToString();
                    }

                    fontWeight = FontWeight.FromOpenTypeWeight(700);


                    if (j == 1 & arraySum[j].ToString() != "0" & stackPanel.Name == "StackPanelDep")
                    {
                        Button buttonAdd = (Button)this.FindName("ButtonAdd");
                        if (buttonAdd != null)
                        {
                            buttonAdd.Visibility = Visibility.Collapsed;
                        }
                    }
                }
                else //Иначе выводим значение DataTable
                {
                    txt        = row[j].ToString();
                    fontWeight = FontWeight.FromOpenTypeWeight(1);
                }

                //Получаем ширину колонки из шапке определенной в xaml
                double width = ((TextBlock)((StackPanel)stackPanel.Children[0]).Children[j]).Width;

                //Формируем TextBlock, который потом вложим в StackPanel
                TextBlock tb = new TextBlock()
                {
                    Margin       = new Thickness(j == 0 ? 0 : 2, 0, 0, 0),
                    TextWrapping = TextWrapping.Wrap,
                    FontSize     = 16,
                    Width        = width,
                    FontWeight   = fontWeight,
                    Text         = txt
                };
                //Формируем StackPanel строку
                stackPanelRow.Children.Add(tb);

                //Суммирую значения колонок, чтобы потом вывести в итоговом StackPanel
                if (j != 0 & arraySum.Length > 0)
                {
                    string itemSum = "0";
                    if (row != null)
                    {
                        itemSum = row[j].ToString();
                    }
                    if (string.IsNullOrEmpty(itemSum))
                    {
                        itemSum = "0";
                    }
                    arraySum[j] += int.Parse(itemSum);
                }
            }

            //Добавляю кнопку редактирование в своднуб таблицу по нормам
            if (stackPanel.Name == "StackPanelDep" & row != null)
            {
                Button editButton = new Button()
                {
                    Margin     = new Thickness(2, 0, 0, 0),
                    Width      = 16,
                    Height     = 16,
                    Background = Brushes.DarkSeaGreen,
                    Content    = ".."
                };
                editButton.Click += editButton_Click;
                stackPanelRow.Children.Add(editButton);
            }

            //Добавляю все что нагенерил в родительскую StackPanel
            stackPanel.Children.Add(stackPanelRowBorder);
        }