예제 #1
1
        /// <summary>
        /// Draw some helpful text.
        /// </summary>
        /// <param name="dc"></param>
        protected virtual void DrawHelpText(DrawingContext dc)
        {
            System.Windows.Media.Typeface backType =
                new System.Windows.Media.Typeface(new System.Windows.Media.FontFamily("sans courier"),
                                                  FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
            System.Windows.Media.FormattedText formatted = new System.Windows.Media.FormattedText(
                                                            "Click & move the mouse to select a capture area.\nENTER/F10: Capture\nBACKSPACE/DEL: Start over\nESC: Exit",
                                                            System.Globalization.CultureInfo.CurrentCulture,
                                                            FlowDirection.LeftToRight,
                                                            backType,
                                                            32.0f,
                                                            new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.White));
            // Make sure the text shows at 0,0 on the primary screen
            System.Drawing.Point primScreen = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Location;
            Point clientBase = PointFromScreen(new Point(primScreen.X + 5, primScreen.Y + 5));
            Geometry textGeo = formatted.BuildGeometry(clientBase);
            dc.DrawGeometry(
                System.Windows.Media.Brushes.White,
                null,
                textGeo);

            dc.DrawGeometry(
                null,
                new System.Windows.Media.Pen(System.Windows.Media.Brushes.White, 1),
                textGeo);
        }
예제 #2
1
 public FontInfo(String Name, double Size, FontFamily Family)
 {
     this.Name = Name;
     this.Size = Size;
     
     this.Family = Family;
     this.Typeface = Family.GetTypefaces().First();
     
 }
예제 #3
0
		public override void Transform()
		{
			base.Transform();
			IElementTextBlock elementText = (IElementTextBlock)Element;
			var height = Rect.Height > Element.BorderThickness ? Rect.Height - Element.BorderThickness : 0;
			var width = Rect.Width > Element.BorderThickness ? Rect.Width - Element.BorderThickness : 0;
			Rect bound = new Rect(Rect.Left + Element.BorderThickness / 2, Rect.Top + Element.BorderThickness / 2, width, height);
			var typeface = new Typeface(new FontFamily(elementText.FontFamilyName), elementText.FontItalic ? FontStyles.Italic : FontStyles.Normal, elementText.FontBold ? FontWeights.Bold : FontWeights.Normal, new FontStretch());
			var formattedText = new FormattedText(elementText.Text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, elementText.FontSize, PainterCache.BlackBrush);
			formattedText.TextAlignment = (TextAlignment)elementText.TextAlignment;
			Point point = bound.TopLeft;
			switch (formattedText.TextAlignment)
			{
				case TextAlignment.Right:
					point = bound.TopRight;
					break;
				case TextAlignment.Center:
					point = new Point(bound.Left + bound.Width / 2, bound.Top);
					break;
			}
			if (_clipGeometry != null)
				_clipGeometry.Rect = bound;
			if (_scaleTransform != null)
			{
				_scaleTransform.CenterX = point.X;
				_scaleTransform.CenterY = point.Y;
				_scaleTransform.ScaleX = bound.Width / formattedText.Width;
				_scaleTransform.ScaleY = bound.Height / formattedText.Height;
			}
			_textDrawing.Geometry = formattedText.BuildGeometry(point);
		}
예제 #4
0
        public Size Measure(string text, double fontSize, Typeface typeface, double maxWidth)
        {
            if (htmlElement == null)
            {
                htmlElement = Document.CreateElement("div");
                style = new HtmlStyleDictionary(htmlElement);

                Document.Body.AppendChild(htmlElement);
            }

            style.SetValue("position", "absolute");
            style.SetValue("visibility", "hidden");
            style.SetFontSize(fontSize, converter);
            style.SetFontFamily(typeface.FontFamily, converter);
            style.SetFontStretch(typeface.Stretch, converter);
            style.SetFontStyle(typeface.Style, converter);
            style.SetFontWeight(typeface.Weight, converter);

            if (maxWidth.IsNaN() || !Double.IsFinite(maxWidth))
            {
                style.SetTextWrapping(TextWrapping.NoWrap, converter);
                style.ClearValue("max-width");
            }
            else
            {
                style.SetTextWrapping(TextWrapping.Wrap, converter);
                style.SetValue("max-width", converter.ToPixelString(maxWidth));
            }

            style.Apply();

            htmlElement.InnerHTML = converter.ToHtmlContentString(text.DefaultIfNullOrEmpty("A"));

            return new Size(text.IsNullOrEmpty() ? 0 : htmlElement.OffsetWidth + 2, htmlElement.OffsetHeight);
        }
예제 #5
0
        public TypefaceListItem(Typeface typeface)
        {
            _displayName = GetDisplayName(typeface);
            _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated;

            FontFamily = typeface.FontFamily;
            FontWeight = typeface.Weight;
            FontStyle = typeface.Style;
            FontStretch = typeface.Stretch;

            var itemLabel = _displayName;

            if (_simulated)
            {
                var formatString = Properties.Resources.ResourceManager.GetString(
                    "simulated",
                    CultureInfo.CurrentUICulture
                    );
                itemLabel = string.Format(formatString, itemLabel);
            }

            Text = itemLabel;
            ToolTip = itemLabel;

            // In the case of symbol font, apply the default message font to the text so it can be read.
            if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily))
            {
                var range = new TextRange(ContentStart, ContentEnd);
                range.ApplyPropertyValue(FontFamilyProperty, SystemFonts.MessageFontFamily);
            }
        }
예제 #6
0
        internal Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle,
            FontWeight fontWeight,
            FontStretch fontStretch, double fontSize)
        {
            var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            GlyphTypeface glyphTypeface;

            if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize);
            }

            double totalWidth = 0;
            double height = 0;

            foreach (var t in text)
            {
                var glyphIndex = glyphTypeface.CharacterToGlyphMap[t];
                var width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
                var glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex] * fontSize;

                if (glyphHeight > height)
                {
                    height = glyphHeight;
                }
                totalWidth += width;
            }
            return new Size(totalWidth, height);
        }
예제 #7
0
파일: MyDecorator.cs 프로젝트: Deiwos3/IMS
        public void AddVisualText(String text, String name_of_element, FontFamily fontFamily, Double fontSize, Point location, Double rotateAngle, Brush brush)
        {
            Typeface typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
            DrawingContext dc;

            DrawingVisual dv = new DrawingVisual();
            FormattedText ft1 = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, fontSize, brush);

            if (location.X == -1)
            {
                location = new Point(this.Width / 2 - ft1.Width / 2, location.Y);
            }
            if (location.Y == -1)
            {
                location = new Point(location.X, this.Height / 2 - ft1.Height / 2);
            }

            RotateTransform rt = new RotateTransform(rotateAngle, location.X + ft1.Width / 2, location.Y + ft1.Height / 2);

            dc = dv.RenderOpen();
            dc.PushTransform(rt);
            dc.DrawText(ft1, location);
            dc.Close();

            this.visuals.Add(new NamedVisual(name_of_element, dv));
            this.AddVisualChild(dv);

        }
예제 #8
0
        public GoBoardPainter()
        {
            Resources.Source = new Uri("pack://application:,,,/gui_wpf;component/GoBoardPainterResources.xaml");

            m_BlackStoneBrush = (Brush)TryFindResource("blackStoneBrush");
            m_WhiteStoneBrush = (Brush)TryFindResource("whiteStoneBrush");
            m_BoardBrush = (Brush)TryFindResource("boardBrush");
            m_StoneShadowBrush = (Brush)TryFindResource("stoneShadowBrush");
            m_WhiteStoneAnnotationPen = (Pen)TryFindResource("whiteStoneAnnotationPen");
            m_BlackStoneAnnotationPen = (Pen)TryFindResource("blackStoneAnnotationPen");
            m_BoardBlackPen = (Pen)TryFindResource("boardBlackPen");
            m_BlackPen = (Pen)TryFindResource("blackPen");
            m_RedPen = (Pen)TryFindResource("redPen");
            m_BlackStoneShadowBrush = (Brush)TryFindResource("blackStoneShadowBrush");
            m_WhiteStoneShadowBrush = (Brush)TryFindResource("whiteStoneShadowBrush");

            m_BoardTypeface = new Typeface("Arial");
            KoPoint.X = -1;
            LastMove.X = -1;
            ForbiddenMove.X = -1;
            DisplayCountedStones = false;
            DisplayMouseOver = true;

            InitializeBoard(this.BoardSize - 1);

            // init tick for clock update
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += timer_Tick;
            timer.Start();
        }
예제 #9
0
        public TypefaceListItem(Typeface typeface)
        {
            _displayName = GetDisplayName(typeface);
            _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated;

            this.FontFamily = typeface.FontFamily;
            this.FontWeight = typeface.Weight;
            this.FontStyle = typeface.Style;
            this.FontStretch = typeface.Stretch;

            string itemLabel = _displayName;

            //if (_simulated)
            //{
            //    string formatString = EpiDashboard.Properties.Resources.ResourceManager.GetString(
            //        "simulated",
            //        CultureInfo.CurrentUICulture
            //        );
            //    itemLabel = string.Format(formatString, itemLabel);
            //}

            this.Text = itemLabel;
            this.ToolTip = itemLabel;

            // In the case of symbol font, apply the default message font to the text so it can be read.
            if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily))
            {
                TextRange range = new TextRange(this.ContentStart, this.ContentEnd);
                range.ApplyPropertyValue(TextBlock.FontFamilyProperty, SystemFonts.MessageFontFamily);
            }
        }
        protected override void DrawVisualThumbnail(System.Windows.Media.DrawingContext drawingContext, out string title, ref BitmapSource icon)
        {
            var aeroColor = (Color)Application.Current.Resources["AeroColor"];
            var aeroBrush = new SolidColorBrush(aeroColor);
            var aeroPen = new Pen(aeroBrush, 7);

            var grayBrush = new SolidColorBrush(Color.FromArgb(255, 0xaf, 0xaf, 0xaf));

            var fontFamily = (FontFamily)Application.Current.Resources["CuprumFont"];
            var typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal);

            const int sourceTextOffset = VisualThumbnailMargin;

            var sourceText = new FormattedText(Name, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                         typeface, 14, grayBrush);
            sourceText.MaxTextWidth = VisualThumbnailWidth - sourceTextOffset - VisualThumbnailMargin;
            sourceText.MaxTextHeight = 32;

            var imageRectangle = new Rect(VisualThumbnailWidth / 2 - 64 / 2, VisualThumbnailHeight / 2 - 64 / 2, 64, 64);

            drawingContext.DrawRectangle(Brushes.White, aeroPen, new Rect(-1, -1, VisualThumbnailWidth + 2, VisualThumbnailHeight + 2));
            drawingContext.DrawImage(Icon, imageRectangle);

            drawingContext.DrawText(sourceText, new Point(sourceTextOffset, VisualThumbnailHeight - VisualThumbnailMargin - 16));

            title = Name + " from " + Source.ApplicationName;
        }
예제 #11
0
        public FontData GetFontData(string fontFamilyName, bool isItalic, bool isBold)
        {
            FontData data = new FontData()
            {
                IsValid = false,
                Bytes = null,
                FontFamilyName = fontFamilyName,
                IsItalic = isItalic,
                IsBold = isBold
            };

            FontFamily fontFamily = new FontFamily(fontFamilyName);
            FontStyle fontStyle = isItalic ? FontStyles.Italic : FontStyles.Normal;
            FontWeight fontWeight = isBold ? FontWeights.Bold : FontWeights.Normal;
            Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, FontStretches.Normal);
            GlyphTypeface glyphTypeface;
            if (typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                using (var memoryStream = new MemoryStream())
                {
                    glyphTypeface.GetFontStream().CopyTo(memoryStream);
                    data.Bytes = memoryStream.ToArray();
                    data.IsValid = true;
                }
            }

            return data;
        }
예제 #12
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var list = value as IReadOnlyCollection<FontFamily>;

            if (list == null)
                return DependencyProperty.UnsetValue;

            var returnList = new List<FontFamily>();
            foreach (FontFamily font in list)
            {
                try
                {
                    // Instantiate a TypeFace object with the font settings you want to use
                    Typeface ltypFace = new Typeface(font, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);

                    // Try to create a GlyphTypeface object from the TypeFace object
                    GlyphTypeface lglyphTypeFace;
                    if (ltypFace.TryGetGlyphTypeface(out lglyphTypeFace))
                    {
                        returnList.Add(font);
                    }
                }
                catch (Exception) {}
            }

            return returnList;
        }
        public override DocumentPage GetPage(int pageNumber)
        {
            // Get the requested page.
            DocumentPage page = flowDocumentPaginator.GetPage(pageNumber);

            // Wrap the page in a Visual. You can then add a transformation and extras.
            ContainerVisual newVisual = new ContainerVisual();
            newVisual.Children.Add(page.Visual);

            // Create a header. 
            DrawingVisual header = new DrawingVisual();
            using (DrawingContext context = header.RenderOpen())
            {
                Typeface typeface = new Typeface("Times New Roman");                
                FormattedText text = new FormattedText("Page " + (pageNumber + 1).ToString(),
                  CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                  typeface, 14, Brushes.Black);
                
                // Leave a quarter-inch of space between the page edge and this text.
                context.DrawText(text, new Point(96*0.25, 96*0.25));
            }
            // Add the title to the visual.
            newVisual.Children.Add(header);

            // Wrap the visual in a new page.
            DocumentPage newPage = new DocumentPage(newVisual);
            return newPage;            
        }
예제 #14
0
        public static Typeface GetTypeface() {
            if (typeface == null) {
                typeface = CreateTypeface();
            }

            return typeface;
        }
예제 #15
0
		public ChatFormatter(Typeface typeface, double fontSize, Brush foreground, IDictionary<string,Brush> palette)
		{
			_runProperties = new CustomTextRunProperties(typeface, fontSize, foreground, Brushes.Transparent, false);
			_paraProperties = new CustomParagraphProperties(_runProperties);
			_formatter = TextFormatter.Create(TextFormattingMode.Display);
			_palette = palette;
		}
예제 #16
0
        public GenericTextRunProperties(
            Typeface typeface,
            double size,
            double hintingSize,
            TextDecorationCollection textDecorations,
            Brush forgroundBrush,
            Brush backgroundBrush,
            BaselineAlignment baselineAlignment,
            TextEffectCollection textEffects,
            CultureInfo culture)
        {
            if (typeface == null)
                throw new ArgumentNullException("typeface");

            ValidateCulture(culture);

            _typeface = typeface;
            _emSize = size;
            _emHintingSize = hintingSize;
            _textDecorations = textDecorations;
            _foregroundBrush = forgroundBrush;
            _backgroundBrush = backgroundBrush;
            _baselineAlignment = baselineAlignment;
            _textEffects = textEffects;
            _culture = culture;
        }
        /// <summary>
        ///     Determines whether or not the text in <paramref name="textBlock" /> is currently being
        ///     trimmed due to width or height constraints.
        /// </summary>
        /// <remarks>Does not work properly when TextWrapping is set to WrapWithOverflow.</remarks>
        /// <param name="textBlock"><see cref="TextBlock" /> to evaluate</param>
        /// <returns><c>true</c> if the text is currently being trimmed; otherwise <c>false</c></returns>
        static bool CalculateIsTextTrimmed(TextBlock textBlock) {
            if (!textBlock.IsArrangeValid)
                return GetIsTextTrimmed(textBlock);

            var typeface = new Typeface(
                textBlock.FontFamily,
                textBlock.FontStyle,
                textBlock.FontWeight,
                textBlock.FontStretch);

            // FormattedText is used to measure the whole width of the text held up by TextBlock container
            var formattedText = new FormattedText(
                textBlock.Text,
                Thread.CurrentThread.CurrentCulture,
                textBlock.FlowDirection,
                typeface,
                textBlock.FontSize,
                textBlock.Foreground) {MaxTextWidth = textBlock.ActualWidth};

            // When the maximum text width of the FormattedText instance is set to the actual
            // width of the textBlock, if the textBlock is being trimmed to fit then the formatted
            // text will report a larger height than the textBlock. Should work whether the
            // textBlock is single or multi-line.
            return formattedText.Height > textBlock.ActualHeight;
        }
예제 #18
0
 static ValueToProcessConverter()
 {
     NormalBrush = new SolidColorBrush(Colors.Orange);
     WarnBrush = new SolidColorBrush(Colors.White);
     TextBrush = new SolidColorBrush(Color.FromRgb(0x74,0x74,0x74));
     SuccessRateTypeface = new Typeface(new FontFamily("MSYH"), new FontStyle(), new FontWeight(), new FontStretch());
 }
예제 #19
0
파일: Font.cs 프로젝트: borkaborka/gmit
 /// <summary>Creates a new <see cref="Font"/> instance from the given typeface and size.</summary>
 public Font(Typeface typeface, double fontSize) {
    Family = typeface.FontFamily;
    Size = fontSize;
    Stretch = typeface.Stretch;
    Style = typeface.Style;
    Weight = typeface.Weight;
 }
예제 #20
0
 /// <summary>
 /// Creates a typeface.
 /// </summary>
 public static Typeface CreateTypeface(XFontFamily family, XFontStyle style)
 {
   FontStyle fontStyle = FontStyleFromStyle(style);
   FontWeight fontWeight = FontWeightFromStyle(style);
   Typeface typeface = new Typeface(family.wpfFamily, fontStyle, fontWeight, FontStretches.Normal);
   return typeface;
 }
예제 #21
0
    Visual CreateContent()
    {
      DrawingContext dc;
      DrawingVisual dv = PrepareDrawingVisual(out dc);

      FontFamily family = new FontFamily("Verdana");
      Typeface typeface;
      FormattedText formattedText;
      Point position = new Point(10, 30);
      string text = String.Empty;
      double emSize = 25;
      Brush brush = Brushes.DarkBlue;

      BeginBox(dc, 1, BoxOptions.Tile);
      typeface = new Typeface(family, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
      text = "ÄÖÜäöüß";
      formattedText = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, emSize, brush);
      dc.DrawText(formattedText, position);
      EndBox(dc);

      BeginBox(dc, 2, BoxOptions.Tile);
      typeface = new Typeface(family, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal);
      text = "§€ÿþ";
      formattedText = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, emSize, brush);
      dc.DrawText(formattedText, position);
      EndBox(dc);

      BeginBox(dc, 3, BoxOptions.Tile);
      typeface = new Typeface(family, FontStyles.Italic, FontWeights.Normal, FontStretches.Normal);
      formattedText = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, emSize, brush);
      dc.DrawText(formattedText, position);
      EndBox(dc);

      BeginBox(dc, 4, BoxOptions.Tile);
      typeface = new Typeface(family, FontStyles.Italic, FontWeights.Bold, FontStretches.Normal);
      formattedText = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, emSize, brush);
      dc.DrawText(formattedText, position);
      EndBox(dc);

      //BeginBox(dc, 5, BoxOptions.Tile);
      //brush = new LinearGradientBrush();
      //brush.GradientStops.Add(new GradientStop(Colors.DarkBlue, 0));
      //brush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
      //brush.GradientStops.Add(new GradientStop(Colors.Red, 1));
      //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
      //EndBox(dc);

      //BeginBox(dc, 6, BoxOptions.Tile);
      //EndBox(dc);

      //BeginBox(dc, 7, BoxOptions.Tile);
      //EndBox(dc);

      //BeginBox(dc, 8, BoxOptions.Tile);
      //EndBox(dc);

      dc.Close();
      return dv;
    }
예제 #22
0
        public FontInfo(String Name, double Size)
        {
            this.Name = Name;
            this.Size = Size;

            this.Family = new FontFamily(Name);
            this.Typeface = new Typeface(Name);
        }
예제 #23
0
        public override double GetMeanline(object backend)
        {
            var t = (TextLayoutBackend)backend;
            var fd = (FontData)ApplicationContext.Toolkit.GetSafeBackend(t.Font);
            var tf = new Typeface (fd.Family, fd.Style, fd.Weight, fd.Stretch);

            return t.FormattedText.Baseline - tf.StrikethroughPosition * WpfFontBackendHandler.GetDeviceUnitsFromPoints (fd.Size);
        }
예제 #24
0
        public static IGeometry Read(string text, Typeface font, double size, Point origin, FlowDirection flowDirection, IGeometryFactory geomFact)
        {
            var formattedText = new FormattedText(text, System.Globalization.CultureInfo.CurrentUICulture,
                                                  flowDirection, font, size, Brushes.Black);

            var geom = formattedText.BuildGeometry(origin);
            return WpfGeometryReader.Read(geom.GetFlattenedPathGeometry(FlatnessFactor, ToleranceType.Relative), geomFact);
        }
예제 #25
0
 public PlatformFontResolverInfo(string faceName, bool mustSimulateBold, bool mustSimulateItalic, WpfFontFamily wpfFontFamily,
     WpfTypeface wpfTypeface, WpfGlyphTypeface wpfGlyphTypeface)
     : base(faceName, mustSimulateBold, mustSimulateItalic)
 {
     _wpfFontFamily = wpfFontFamily;
     _wpfTypeface = wpfTypeface;
     _wpfGlyphTypeface = wpfGlyphTypeface;
 }
예제 #26
0
        public static ImageSource ToFontAwesomeIcon(this string text, Brush foreBrush, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch)
        {
            var fontFamily = new FontFamily("/GitWorkItems;component/Resources/#FontAwesome");
            if (fontFamily != null && !String.IsNullOrEmpty(text))
            {
                //premier essai, on charge la police directement
                Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

                GlyphTypeface glyphTypeface;
                if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
                {
                    //si ça ne fonctionne pas (et pour le mode design dans certains cas) on ajoute l'uri pack://application
                    typeface = new Typeface(new FontFamily(new Uri("pack://application:,,,"), fontFamily.Source), fontStyle, fontWeight, fontStretch);
                    if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
                        throw new InvalidOperationException("No glyphtypeface found");
                }

                //détermination des indices/tailles des caractères dans la police
                ushort[] glyphIndexes = new ushort[text.Length];
                double[] advanceWidths = new double[text.Length];

                for (int n = 0; n < text.Length; n++)
                {
                    ushort glyphIndex;
                    try
                    {
                        glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];

                    }
                    catch (Exception)
                    {
                        glyphIndex = 42;
                    }
                    glyphIndexes[n] = glyphIndex;

                    double width = glyphTypeface.AdvanceWidths[glyphIndex] * 1.0;
                    advanceWidths[n] = width;
                }

                try
                {

                    //création de l'objet DrawingImage (compatible avec Imagesource) à partir d'un glyphrun
                    GlyphRun gr = new GlyphRun(glyphTypeface, 0, false, 1.0, glyphIndexes,
                                                                         new Point(0, 0), advanceWidths, null, null, null, null, null, null);

                    GlyphRunDrawing glyphRunDrawing = new GlyphRunDrawing(foreBrush, gr);
                    return new DrawingImage(glyphRunDrawing);
                }
                catch (Exception ex)
                {
                    // ReSharper disable LocalizableElement
                    Console.WriteLine("Error in generating Glyphrun : " + ex.Message);
                    // ReSharper restore LocalizableElement
                }
            }
            return null;
        }
예제 #27
0
 public DocumentPaginatorWrapper(DocumentPaginator paginator, Size pageSize, Size margin)
 {
     m_PageSize = pageSize;
     m_Margin = margin;
     m_Paginator = paginator;
     m_Paginator.PageSize = new Size(PageSize.Width - margin.Width * 2,
                                     PageSize.Height - margin.Height * 2);
     m_Typeface = new Typeface("Times New Roman");
 }
예제 #28
0
        static EmojiCharacters()
        {
            var typeface = new System.Windows.Media.Typeface(EmojiFontName);

            _Emojis = new Dictionary <int, EmojiCharacter>();
            if (typeface.TryGetGlyphTypeface(out _Typeface))
            {
                using (var s = _Typeface.GetFontStream())
                {
                    var r          = new Typography.OpenFont.OpenFontReader();
                    var m_openfont = r.Read(s, Typography.OpenFont.ReadFlags.Full);

                    _UnitsPerEm = m_openfont.UnitsPerEm;

                    var  colrTable = m_openfont.COLRTable;
                    int  palette = 0; // FIXME: support multiple palettes?
                    var  brushs = new Dictionary <Color, Brush>();
                    byte R, G, B, A;
                    foreach (var kv in _Typeface.CharacterToGlyphMap)
                    {
                        var glyphIndex = kv.Value;
                        if (colrTable.LayerIndices.TryGetValue(glyphIndex, out var layer_index))
                        {
                            int endIndex = layer_index + colrTable.LayerCounts[glyphIndex];
                            var layers   = new EmojiGlyphLayer[endIndex - layer_index];
                            for (int i = layer_index; i < endIndex; ++i)
                            {
                                ushort sub_gid = colrTable.GlyphLayers[i];
                                int    cid     = m_openfont.CPALTable.Palettes[palette] + colrTable.GlyphPalettes[i];
                                m_openfont.CPALTable.GetColor(cid, out R, out G, out B, out A);
                                var color = Color.FromArgb(A, R, G, B);
                                if (!brushs.TryGetValue(color, out Brush brush))
                                {
                                    brush = new SolidColorBrush(color);
                                    brushs.Add(color, brush);
                                }
                                layers[i - layer_index] = new EmojiGlyphLayer()
                                {
                                    Brush = brush,
                                    //Color = Color.FromArgb(A, R, G, B),
                                    LayerIndex = sub_gid
                                };
                            }

                            var glyph = m_openfont.Lookup(kv.Key);
                            var width = glyph.OriginalAdvanceWidth;
                            if (!glyph.HasOriginalAdvancedWidth)
                            {
                                width = m_openfont.GetHAdvanceWidthFromGlyphIndex(glyphIndex);
                            }
                            _Emojis.Add(kv.Key, new EmojiCharacter(layers, width,
                                                                   Char.ConvertFromUtf32(kv.Key).Length));
                        }
                    }
                }
            }
        }
 public MainWindow()
 {
     InitializeComponent();
     DataContext = _viewModel = new MainViewModel();
     _viewModel.PropertyChanged += ViewModelPropertyChanged;
     _typeface = new Typeface(QueryTextBox.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
     AutoCompletePopup.Opened += AutoCompletePopupOpened;
     AutoCompletePopup.Closed += AutoCompletePopupClosed;
 }
예제 #30
0
 public FontRendering()
 {
     _fontSize = 12.0f;
     _alignment = TextAlignment.Left;
     _textDecorations = new TextDecorationCollection();
     _textColor = Brushes.Black;
     _typeface = new Typeface(new FontFamily("Arial"),
        FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
 }
예제 #31
0
        public static Size GetScreenSize(this string text, FontFamily fontFamily, double fontSize, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch) {
            fontFamily = fontFamily ?? new TextBlock().FontFamily;
            fontSize = fontSize > 0 ? fontSize : new TextBlock().FontSize;

            var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            var ft = new FormattedText(text ?? string.Empty, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontSize, Brushes.Black);

            return new Size(ft.Width, ft.Height);
        }
예제 #32
0
        public static XGlyphTypeface GetOrCreateFromWpf(WpfTypeface wpfTypeface)
        {
#if DEBUG
            if (wpfTypeface.FontFamily.Source == "Segoe UI Semilight")
            {
                wpfTypeface.GetType();
            }
#endif
            //string typefaceKey = ComputeKey(wpfTypeface);
            //XGlyphTypeface glyphTypeface;
            //if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
            //{
            //    // We have the glyph typeface already in cache.
            //    return glyphTypeface;
            //}

            // Lock around TryGetGlyphTypeface and AddGlyphTypeface.
            try
            {
                Lock.EnterFontFactory();

                // Create WPF glyph typeface.
                WpfGlyphTypeface wpfGlyphTypeface;
                if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
                {
                    return(null);
                }

                string typefaceKey = ComputeKey(wpfGlyphTypeface);

                string name1 = wpfGlyphTypeface.DesignerNames[FontHelper.CultureInfoEnUs];
                string name2 = wpfGlyphTypeface.FaceNames[FontHelper.CultureInfoEnUs];
                string name3 = wpfGlyphTypeface.FamilyNames[FontHelper.CultureInfoEnUs];
                string name4 = wpfGlyphTypeface.ManufacturerNames[FontHelper.CultureInfoEnUs];
                string name5 = wpfGlyphTypeface.Win32FaceNames[FontHelper.CultureInfoEnUs];
                string name6 = wpfGlyphTypeface.Win32FamilyNames[FontHelper.CultureInfoEnUs];

                XGlyphTypeface glyphTypeface;
                if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
                {
                    // We have the glyph typeface already in cache.
                    return(glyphTypeface);
                }

                XFontFamily fontFamily = XFontFamily.GetOrCreateFromWpf(wpfTypeface.FontFamily);
                XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);

                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource,
                                                   (XStyleSimulations)wpfGlyphTypeface.StyleSimulations,
                                                   wpfTypeface, wpfGlyphTypeface);
                GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface);

                return(glyphTypeface);
            }
            finally { Lock.ExitFontFactory(); }
        }
예제 #33
0
        /// <summary>
        /// Creates a typeface.
        /// </summary>
        public static Typeface CreateTypeface(WpfFontFamily family, XFontStyle style)
        {
            // BUG: does not work with fonts that have others than the four default styles
            WpfFontStyle  fontStyle  = FontStyleFromStyle(style);
            WpfFontWeight fontWeight = FontWeightFromStyle(style);

#if !SILVERLIGHT
            WpfTypeface typeface = new WpfTypeface(family, fontStyle, fontWeight, FontStretches.Normal);
#else
            WpfTypeface typeface = null;
#endif
            return(typeface);
        }
        /// <summary>
        /// Width and height in terms of CELLS, not pixels.
        /// </summary>
        public WPFFormattedTextViewer(int width, int height,
                                      int cellWidth, int cellHeight, double emSize,
                                      Theme theme)
            : base(width, height, theme)
        {
            typeface = new Media.Typeface("Consolas");

            CellWidth  = cellWidth;
            CellHeight = cellHeight;

            this.emSize = emSize;

            SetSize(width, height);
        }
예제 #35
0
        public static List <LwPolylineModel> BuildTextPath(MText mText, System.Windows.Media.Typeface typeface, int fontSize)
        {
            string text    = mText.PlainText();
            var    positon = new System.Windows.Point(mText.Position.X, -mText.Position.Y);
            var    data    = GetTextGeometry(text, positon, 360 - mText.Rotation, typeface, fontSize);
            var    figures = data.GetOutlinedPathGeometry().Figures;
            SortedList <double, LwPolylineModel> sortLines = new SortedList <double, LwPolylineModel>();

            foreach (var fig in figures)
            {
                LwPolylineModel line = new LwPolylineModel();
                line.IsFill = fig.IsClosed;
                foreach (var seg in fig.Segments)
                {
                    if (seg is PolyLineSegment)
                    {
                        var segs   = seg as PolyLineSegment;
                        var points = segs.Points.Select(e =>
                        {
                            var point = GetSymmetryPointByLine(new UnitPoint(e.X, e.Y), 0, 1, 0);
                            return(new UnitPointBulge(point));
                        }).ToList();
                        line.Points.AddRange(points);
                    }
                    else if (seg is ArcSegment)
                    {
                    }
                    else if (seg is BezierSegment)
                    {
                    }
                    else if (seg is LineSegment)
                    {
                    }
                    else if (seg is PolyBezierSegment)
                    {
                    }
                    else if (seg is PolyQuadraticBezierSegment)
                    {
                    }
                    else if (seg is QuadraticBezierSegment)
                    {
                    }
                    else
                    {
                    }
                }
                sortLines.Add(Distance(new UnitPoint(mText.Position.X, -mText.Position.Y), new UnitPoint(fig.StartPoint.X, fig.StartPoint.Y), true), line);
            }
            return(sortLines.Values.ToList());
        }
예제 #36
0
        XGlyphTypeface(string key, XFontFamily fontFamily, XFontSource fontSource, XStyleSimulations styleSimulations, WpfTypeface wpfTypeface, WpfGlyphTypeface wpfGlyphTypeface)
        {
            _key              = key;
            _fontFamily       = fontFamily;
            _fontSource       = fontSource;
            _styleSimulations = styleSimulations;

            _fontface = OpenTypeFontface.CetOrCreateFrom(fontSource);
            Debug.Assert(ReferenceEquals(_fontSource.Fontface, _fontface));

            _wpfTypeface      = wpfTypeface;
            _wpfGlyphTypeface = wpfGlyphTypeface;

            Initialize();
        }
        private Media.GlyphTypeface LoadTypeface(string getFamily, int getFontSize, int getCellWidth, int getCellHeight)
        {
            Media.GlyphTypeface glyphTypeface;

            Media.FontFamily family   = new Media.FontFamily(getFamily);
            Media.Typeface   typeface = new Media.Typeface(family,
                                                           FontStyles.Normal,
                                                           FontWeights.Normal,
                                                           FontStretches.Normal);

            typeface.TryGetGlyphTypeface(out glyphTypeface);

            fontSize   = getFontSize;
            CellWidth  = getCellWidth;
            CellHeight = getCellHeight;

            return(glyphTypeface);
        }
예제 #38
0
        private GlyphTypeface GetGlyphTypeface(string name)
        {
            var typeface = new System.Windows.Media.Typeface(name);

            if (typeface.TryGetGlyphTypeface(out var gtf))
            {
                return(gtf);
            }

            try
            {
                return(new GlyphTypeface(new Uri(name)));
            }
            catch
            {
                return(null);
            }
        }
예제 #39
0
        private GlyphTypeface GetGlyphTypeface(string first_candidate)
        {
            IList <string> all_candidates = new List <string>();

            if (first_candidate != null)
            {
                all_candidates.Add(first_candidate);
            }

            // Some good Emoji font candidates
            all_candidates.Add("Segoe UI Emoji");
            all_candidates.Add(@"c:\Windows\Fonts\seguiemj.ttf");

            // Maybe try the Firefox EmojiOne font?
            var firefox_key  = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\firefox.exe";
            var firefox_path = Microsoft.Win32.Registry.GetValue(firefox_key, "Path", null);

            if (firefox_path is string)
            {
                all_candidates.Add((firefox_path as string) + @"\fonts\EmojiOneMozilla.ttf");
            }

            // Last resort fallbacks
            all_candidates.Add("Segoe UI Symbol"); // for older versions of Windows
            all_candidates.Add("Arial");           // available since Windows 3.1!

            foreach (var name in all_candidates)
            {
                var typeface = new System.Windows.Media.Typeface(name);
                if (typeface.TryGetGlyphTypeface(out var gtf))
                {
                    return(gtf);
                }

                try
                {
                    return(new GlyphTypeface(new Uri(name)));
                }
                catch {}
            }

            return(null);
        }
        /// <summary>
        /// Create a WPF GlyphTypeface and retrieve font data from it.
        /// </summary>
        internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions,
                                                     out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey)
        {
            if (string.IsNullOrEmpty(typefaceKey))
            {
                typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
            }
            XFontStyle style = fontResolvingOptions.FontStyle;

#if DEBUG
            if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0 &&
                (style & XFontStyle.BoldItalic) == XFontStyle.Italic)
            {
                familyName.GetType();
            }
#endif

            // Use WPF technique to create font data.
            wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily);
#if DEBUG__
            if (wpfTypeface != null)
            {
                WpfGlyphTypeface          glyphTypeface;
                ICollection <WpfTypeface> list = wpfFontFamily.GetTypefaces();
                foreach (WpfTypeface tf in list)
                {
                    if (!tf.TryGetGlyphTypeface(out glyphTypeface))
                    {
                        Debug - Break.Break();
                    }
                }

                //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface))
                //    throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }
#endif
            if (wpfFontFamily == null)
            {
                wpfFontFamily = new WpfFontFamily(familyName);
            }

            if (wpfTypeface == null)
            {
                wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style);
            }

            // Let WPF choose the right glyph typeface.
            if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
            {
                throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }

            // Get or create the font source and cache it unter the specified typeface key.
            XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);
            return(fontSource);
        }
예제 #41
0
        public static XGlyphTypeface GetOrCreateFrom(string familyName, FontResolvingOptions fontResolvingOptions)
        {
            // Check cache for requested type face.
            string         typefaceKey = ComputeKey(familyName, fontResolvingOptions);
            XGlyphTypeface glyphTypeface;

            if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
            {
                // Just return existing one.
                return(glyphTypeface);
            }

            // Resolve typeface by FontFactory.
            FontResolverInfo fontResolverInfo = FontFactory.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey);

            if (fontResolverInfo == null)
            {
                // No fallback - just stop.
                throw new InvalidOperationException("No appropriate font found.");
            }

#if CORE || GDI
            GdiFont gdiFont = null;
#endif
#if WPF
            WpfFontFamily    wpfFontFamily    = null;
            WpfTypeface      wpfTypeface      = null;
            WpfGlyphTypeface wpfGlyphTypeface = null;
#endif
#if UWP
            // Nothing to do.
#endif
            // Now create the font family at the first.
            XFontFamily fontFamily;
            PlatformFontResolverInfo platformFontResolverInfo = fontResolverInfo as PlatformFontResolverInfo;
            if (platformFontResolverInfo != null)
            {
#if CORE || GDI
                // $TODO THHO Lock???
                // Reuse GDI+ font from platform font resolver.
                gdiFont    = platformFontResolverInfo.GdiFont;
                fontFamily = XFontFamily.GetOrCreateFromGdi(gdiFont);
#endif
#if WPF
#if !SILVERLIGHT
                // Reuse WPF font family created from platform font resolver.
                wpfFontFamily    = platformFontResolverInfo.WpfFontFamily;
                wpfTypeface      = platformFontResolverInfo.WpfTypeface;
                wpfGlyphTypeface = platformFontResolverInfo.WpfGlyphTypeface;
                fontFamily       = XFontFamily.GetOrCreateFromWpf(wpfFontFamily);
#else
                fontFamily = XFontFamily.GetOrCreateFromWpf(new WpfFontFamily(familyName));
#endif
#endif
#if NETFX_CORE || UWP
                fontFamily = null;
#endif
            }
            else
            {
                // Create new and exclusively used font family for custom font resolver retrieved font source.
                fontFamily = XFontFamily.CreateSolitary(fontResolverInfo.FaceName);
            }

            // We have a valid font resolver info. That means we also have an XFontSource object loaded in the cache.
            ////XFontSource fontSource = FontFactory.GetFontSourceByTypefaceKey(fontResolverInfo.FaceName);
            XFontSource fontSource = FontFactory.GetFontSourceByFontName(fontResolverInfo.FaceName);
            Debug.Assert(fontSource != null);

            // Each font source already contains its OpenTypeFontface.
#if CORE || GDI
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, gdiFont);
#endif
#if WPF
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, wpfTypeface, wpfGlyphTypeface);
#endif
#if NETFX_CORE || UWP
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations);
#endif
#if __IOS__
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontSource);
#endif
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontSource);
            GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface);

            return(glyphTypeface);
        }
예제 #42
0
        public string Text2Path(String strText, string strCulture, bool LtoR, string strTypeFace, int nSize, Thickness masks)
        {
            // Set up the Culture
            if (strCulture == "")
            {
                strCulture = "en-us";
            }
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(strCulture);


            // Set up the flow direction
            System.Windows.FlowDirection fd;
            if (LtoR)
            {
                fd = FlowDirection.LeftToRight;
            }
            else
            {
                fd = FlowDirection.RightToLeft;
            }

            // Set up the font family from the parameter
            FontFamily ff = new FontFamily(strTypeFace);

            // Create the new typeface
            System.Windows.Media.Typeface tf = new System.Windows.Media.Typeface(ff,

                                                                                 FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);


            // Create a formatted text object from the text,

            // culture, flowdirection, typeface, size and black


            FormattedText t = new FormattedText(strText, ci, fd, tf, nSize,

                                                System.Windows.Media.Brushes.Black);

            // Build a Geometry out of this
            Geometry g = t.BuildGeometry(new Point(0, 0));

            // Get the Path info from the geometry
            PathGeometry p     = g.GetFlattenedPathGeometry();
            var          x     = nSize - masks.Left - masks.Right;
            var          y     = nSize - masks.Top - masks.Bottom;
            var          size  = new Size(x < 0 ? 0 : x, y < 0 ? 0 : y);
            var          rectv = new Rect(new Point(masks.Left, masks.Top), size);

            RectangleGeometry rg = new RectangleGeometry(rectv);
            var cg = new CombinedGeometry(p, rg);

            cg.GeometryCombineMode = GeometryCombineMode.Intersect;



            p = cg.GetFlattenedPathGeometry();

            // Return the path info
            return(p.ToString());
        }
예제 #43
0
        private void FontDialog_Load(object sender, EventArgs e)
        {
            IsLoading = true;

            #region Fetch All Typefaces
            var FamilyList = ExtensionMethods.NetCharmExtensions.GetFamilies();
            //var FamilyList = ExtensionMethods.NetCharmExtensions.FamilyList;
            //foreach ( var f in Media.Fonts.SystemTypefaces )
            //{
            //    var f_key = f.FontFamily.FamilyNames.ContainsKey(locale_enkey)? f.FontFamily.FamilyNames[locale_enkey] : f.FontFamily.FamilyNames.First().Value;

            //    try
            //    {
            //        Media.GlyphTypeface gtf = null;
            //        f.TryGetGlyphTypeface( out gtf );

            //        var facelist = new Dictionary<string, Media.Typeface>();
            //        if(f.FaceNames.ContainsKey(locale_enkey))
            //            facelist[f.FaceNames[locale_enkey]] = f;
            //        else
            //            facelist[f.FaceNames.First().Value] = f;

            //        if ( f.FaceNames.ContainsKey( locale_uikey ) )
            //            facelist[f.FaceNames[locale_uikey]] = f;

            //        if ( gtf != null )
            //        {
            //            //gtf.Win32FaceNames
            //            if ( gtf.Win32FaceNames.ContainsKey( locale_eninfo ) )
            //                facelist[gtf.Win32FaceNames[locale_eninfo]] = f;
            //            else
            //                facelist[gtf.Win32FaceNames.First().Value] = f;

            //            if ( gtf.Win32FaceNames.ContainsKey( locale_uiinfo ) )
            //                facelist[gtf.Win32FaceNames[locale_uiinfo]] = f;
            //        }

            //        FamilyList[f_key] = facelist;
            //        if ( f.FontFamily.FamilyNames.ContainsKey( locale_enkey ) )
            //            FamilyList[f.FontFamily.FamilyNames[locale_enkey]] = facelist;
            //        else
            //            FamilyList[f.FontFamily.FamilyNames.First().Value] = facelist;

            //        if ( f.FontFamily.FamilyNames.ContainsKey( locale_uikey ) )
            //            FamilyList[f.FontFamily.FamilyNames[locale_uikey]] = facelist;

            //        if ( gtf != null )
            //        {
            //            //gtf.Win32FamilyNames
            //            foreach ( var wfn in gtf.Win32FamilyNames )
            //            {
            //                if ( !FamilyList.ContainsKey( wfn.Value ) )
            //                    FamilyList[wfn.Value] = facelist;
            //            }
            //        }
            //    }
            //    catch ( Exception )
            //    {
            //        FamilyList[f_key] = null;
            //    }
            //}

            //StringBuilder sb = new StringBuilder();
            //foreach(var f in FamilyList )
            //{
            //    sb.AppendLine( f.Key.ToString() );
            //    foreach(var ff in f.Value)
            //    {
            //        sb.AppendLine( $"  {ff.Key}*{ff.Value.ToString()}");
            //    }
            //}
            //System.IO.File.WriteAllText( "typefaces.txt", sb.ToString() );
            #endregion

            #region Make Font List
            families.Clear();
            foreach (var ff in Media.Fonts.SystemFontFamilies)
            {
                var locale_key = ff.FamilyNames.Keys.First();
                if (ff.FamilyNames.ContainsKey(locale_enkey))
                {
                    locale_key = locale_enkey;
                }
                var familyName = ff.FamilyNames.ContainsKey(locale_uikey) ? ff.FamilyNames[locale_uikey] : ff.FamilyNames[locale_key];

                var item = new ListViewItem(familyName);
                item.Text = familyName;
                //item.Tag = ff;
                if (!FamilyList.ContainsKey(familyName))
                {
                    var tl = new Dictionary <string, Media.Typeface>();
                    foreach (var t in ff.FamilyTypefaces)
                    {
                        Media.Typeface tf = new Media.Typeface(ff, t.Style, t.Weight, t.Stretch);
                        tl[t.AdjustedFaceNames[locale_key]] = tf;
                    }
                    FamilyList[familyName] = tl;
                }
                item.Tag = FamilyList[familyName];
                families.Add(item);
            }
            families.Sort(CompareItemText);
            #endregion

            #region Fetch All Typeface List
            //TypefaceList = (Dictionary < string, Media.Typeface > )Media.Fonts.SystemTypefaces.Select( face => new { Key = $"{face.FontFamily.FamilyNames[locale_enkey]}*{face.FaceNames[locale_enkey]}", Value = face } );
            #endregion

            #region Init Font Color
            colorGrid.Color = FontColor;
            #endregion

            #region Init Font Size List
            lbSize.Text = FontSize.ToString();
            #endregion

            #region Init Font Style List
            lvStyle.Items.Clear();
            if (lvStyle.Columns.Count == 0)
            {
                lvStyle.Columns.Add("Font Style");
                lvStyle.Columns[0].Width = lvStyle.ClientSize.Width;
                //lvStyle.Columns[0].AutoResize( ColumnHeaderAutoResizeStyle.HeaderSize );
            }
            lvStyle.View = View.Details;
            #endregion

            #region Init Font Family List
            lvFamily.Clear();
            if (lvFamily.Columns.Count == 0)
            {
                lvFamily.Columns.Add("Font Family");
                lvFamily.Columns[0].Width = lvFamily.ClientSize.Width;
                //lvStyle.Columns[0].AutoResize( ColumnHeaderAutoResizeStyle.ColumnContent );
            }
            lvFamily.View            = View.Details;
            lvFamily.VirtualListSize = families.Count;
            lvFamily.VirtualMode     = true;
            #endregion

            #region Selected default font
            int idx = 0;
            if (string.IsNullOrEmpty(_familyName))
            {
                _familyName = SelectedFont.FontFamily.Name;
            }
            string ffn  = UseFont ? SelectedFont.Name : _familyName;
            var    lvis = families.AsParallel().Where(o => { return(string.Equals(o.Text, ffn, StringComparison.CurrentCultureIgnoreCase)); });
            if (lvis.Count() > 0)
            {
                ListViewItem lvi = lvis.First();
                idx = families.IndexOf(lvi);
                lvFamily.Select();
                lvFamily.EnsureVisible(idx);
                lvFamily.FocusedItem = lvFamily.FindItemWithText(ffn, false, idx);
                if (lvFamily.FocusedItem != null)
                {
                    lvFamily.FocusedItem.Selected = true;
                }
            }
            #endregion

            #region Add family supported styles
            var ffc = (Dictionary <string, Media.Typeface>)families[idx].Tag;

            //curFamily = ffc;
//            var ffcn = ffc.FamilyNames.ContainsKey(locale_uikey) ? ffc.FamilyNames[locale_uikey] : ffc.FamilyNames[locale_enkey];
            curFamilyName = lvFamily.FocusedItem is ListViewItem ? lvFamily.FocusedItem.Text : families[idx].Text;
            //curFamilyName = lvFamily.FocusedItem.Text;

            styleSamples.Clear();
            lvStyle.Items.Clear();
            foreach (var f in ffc) //.Reverse() )
            {
                var facename = f.Key.Replace("250", "Thin").Replace("350", "Regular");
                var item     = new ListViewItem(f.Key);
                item.Text = string.Join(" ", facename.Split().Select(o => o._()));
                item.Tag  = facename;
                lvStyle.Items.Add(item);
            }

            if (lvStyle.Items.Count > 0)
            {
                if (!UseFont && !string.IsNullOrEmpty(_typefaceName))
                {
                    var fcns = _typefaceName.Split();
                    var fs   = _typefaceName.ToFontStyle();

                    if (fs.HasFlag(FontStyle.Underline))
                    {
                        chkEffectUnderline.Checked = true;
                    }

                    if (fs.HasFlag(FontStyle.Strikeout))
                    {
                        chkEffectStrikeout.Checked = true;
                    }

                    List <string> faces = new List <string>();
                    foreach (var s in fcns)
                    {
                        if (!string.Equals(s, "underline", StringComparison.CurrentCultureIgnoreCase) &&
                            !string.Equals(s, "strikeout", StringComparison.CurrentCultureIgnoreCase))
                        {
                            faces.Add(s._());
                        }
                    }
                    curFaceName = string.Join(" ", faces);
                    var lvs = lvStyle.FindItemWithText(curFaceName);
                    if (lvs is ListViewItem)
                    {
                        lvs.Selected = true;
                        edStyle.Text = lvs.Text;
                    }
                    else
                    {
                        lvStyle.Items[0].Selected = true;
                        edStyle.Text = lvStyle.Items[0].Text;
                        curFaceName  = (string)lvStyle.Items[0].Tag;
                    }
                }
                else
                {
                    lvStyle.Items[0].Selected = true;
                    edStyle.Text = lvStyle.Items[0].Text;
                    curFaceName  = (string)lvStyle.Items[0].Tag;
                }
            }
            lvStyle.Update();
            #endregion

            IsLoading = false;
            Preview();
        }
예제 #44
0
        private void lvFamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvFamily.FocusedItem is ListViewItem)
            {
                //lvFamily.FocusedItem.EnsureVisible();

                int idx = lvFamily.FocusedItem.Index;

                //var ff = (Media.FontFamily)families[idx].Tag;
                var ff = (Dictionary <string, Media.Typeface>)families[idx].Tag;
                curFamily = ff.First().Value;
                //curFamily = ff;
                //curFamilyName = ff.FamilyNames.ContainsKey( locale_uikey ) ? ff.FamilyNames[locale_uikey] : ff.FamilyNames[locale_enkey];
                //curFamilyName = ff.FamilyNames[locale_enkey];
                curFamilyName = lvFamily.FocusedItem.Text;

                lvStyle.BeginUpdate();
                #region Add family supported styles
                styleSamples.Clear();
                lvStyle.Items.Clear();
                //foreach ( var typeface in ff.FamilyTypefaces )
                var seps = new char[] { ' ', '-', '_' };
                foreach (var f in ff) //.Reverse() )
                {
                    var facename = f.Key;
                    var item     = new ListViewItem(f.Key);
                    item.Text = string.Join(" ", facename.Split(seps).Select(o => o._()));
                    item.Text = string.IsNullOrEmpty(item.Text) ? this._("Regular") : this._(item.Text);
                    item.Text = Regex.Replace(item.Text, @"(特|极|半|窄) (.)(体)", "$1$2", RegexOptions.IgnoreCase);
                    item.Tag  = facename;
                    lvStyle.Items.Add(item);
                }
                if (lvStyle.Items.Count > 0)
                {
                    lvStyle.Items[0].Selected = true;
                    edStyle.Text = lvStyle.Items[0].Text;
                    edStyle.Tag  = lvStyle.Items[0].Tag;
                    curFaceName  = (string)lvStyle.Items[0].Tag;
                }
                #endregion
                lvStyle.EndUpdate();

                #region Add family sizes

                #endregion

                #region Add family charsets
                List <string> charsets    = new List <string>();
                List <string> charsets_ui = new List <string>();
                foreach (var kv in ff.Values.First().FontFamily.FamilyNames)
                {
                    //charsets.Add( kv.Key.IetfLanguageTag );
                    //var charset = CultureInfo.GetCultureInfoByIetfLanguageTag( kv.Key.IetfLanguageTag ).DisplayName;
                    var charset = CultureInfo.GetCultureInfo(kv.Key.IetfLanguageTag).DisplayName;
                    charsets_ui.Add(charset);
                    charsets.Add(kv.Key.IetfLanguageTag);
                }
                cbCharset.Items.Clear();
                cbCharset.Tag = charsets;
                cbCharset.Items.AddRange(charsets_ui.Distinct().ToArray());
                cbCharset.Text          = CultureInfo.CurrentUICulture.DisplayName;
                cbCharset.SelectedIndex = cbCharset.SelectedIndex < 0 ? 0 : cbCharset.SelectedIndex;
                _locale = charsets[cbCharset.SelectedIndex];
                #endregion

                if (!lvFamily.FocusedItem.Text.StartsWith(edFamily.Text, StringComparison.CurrentCultureIgnoreCase))
                {
                    edFamily.Text = lvFamily.FocusedItem.Text;
                }

                _familyName = curFamilyName;
                Preview();
            }
        }
예제 #45
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //figure out how wide the treeview is so we can wrap the text
            var typeFace = new System.Windows.Media.Typeface(theTreeView.FontFamily.ToString());
            var ft       = new FormattedText("xxxxxxxxxx", System.Globalization.
                                             CultureInfo.CurrentCulture,
                                             theTreeView.FlowDirection,
                                             typeFace,
                                             theTreeView.FontSize,
                                             theTreeView.Foreground,
                                             VisualTreeHelper.GetDpi(this).PixelsPerDip);

            charsPerLine  = (int)(10 * theTreeView.ActualWidth / ft.Width);
            charsPerLine -= 10; //leave a little margin...the indent is calculated for individual entries


            try
            {
                string    root   = textBox1.Text;
                ModuleUKS parent = (ModuleUKS)base.ParentModule;
                if (!updateFailed)
                {
                    expandedItems.Clear();
                    FindExpandedItems(theTreeView.Items, "");
                }
                updateFailed = false;
                theTreeView.Items.Clear();
                int          childCount = 0;
                int          refCount   = 0;
                List <Thing> uks        = parent.GetTheUKS();
                foreach (Thing t1 in uks)
                {
                    childCount += t1.Children.Count;
                    refCount   += t1.References.Count;
                }
                statusLabel.Content = uks.Count + " Nodes  " + (childCount + refCount) + " Edges";
                Thing t = parent.Labeled(root);
                if (t != null)
                {
                    totalItemCount = 0;
                    TreeViewItem tvi = new TreeViewItem {
                        Header = t.Label
                    };
                    tvi.IsExpanded = true; //always expand the top-level item
                    theTreeView.Items.Add(tvi);
                    totalItemCount++;
                    tvi.MouseRightButtonDown += Tvi_MouseRightButtonDown;
                    AddChildren(t, tvi, 0, t.Label);
                }
                else if (root == "") //search for unattached Things
                {
                    try              //ignore problems of collection modified
                    {
                        foreach (Thing t1 in uks)
                        {
                            if (t1.Parents.Count == 0)
                            {
                                TreeViewItem tvi = new TreeViewItem {
                                    Header = t1.Label
                                };
                                theTreeView.Items.Add(tvi);
                            }
                        }
                    }
                    catch { updateFailed = true; }
                }
            }
            catch
            {
                updateFailed = true;
            }
        }
예제 #46
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontGetCount = delegate()
            {
                int count = 0;
                MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count);
                return(count);
            };

            ioctls.maFontGetName = delegate(int _index, int _buffer, int _bufferLen)
            {
                if (_index > ioctls.maFontGetCount())
                {
                    return(MoSync.Constants.RES_FONT_INDEX_OUT_OF_BOUNDS);
                }
                else
                {
                    String fontName = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        int count = 0;
                        System.Collections.Generic.IEnumerator <Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator();
                        while (count < _index)
                        {
                            en.MoveNext();
                            count++;
                        }
                        System.Windows.Media.Typeface currentTypeFace = en.Current;
                        System.Windows.Media.GlyphTypeface currentGlyph;
                        currentTypeFace.TryGetGlyphTypeface(out currentGlyph);
                        fontName = currentGlyph.FontFileName;
                        fontName = (fontName.Split('.'))[0];
                    });

                    if (fontName.Length > _bufferLen)
                    {
                        return(MoSync.Constants.RES_FONT_INSUFFICIENT_BUFFER);
                    }
                    core.GetDataMemory().WriteStringAtAddress(_buffer, fontName, _bufferLen);
                    return(MoSync.Constants.RES_FONT_OK);
                }
            };

            ioctls.maFontLoadWithName = delegate(int _postScriptName, int _size)
            {
                String        fontName      = core.GetDataMemory().ReadStringAtAddress(_postScriptName);
                Typeface      typeface      = null;
                GlyphTypeface glyphTypeface = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    int count = Fonts.SystemTypefaces.Count;
                    System.Collections.Generic.IEnumerator <Typeface> en = Fonts.SystemTypefaces.GetEnumerator();
                    while (count != 0)
                    {
                        typeface = en.Current;
                        if (typeface.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            if (glyphTypeface.FontFileName.StartsWith(fontName))
                            {
                                break;
                            }
                        }
                        en.MoveNext();
                        count--;
                    }
                });

                if (glyphTypeface == null)
                {
                    return(-2);
                }

                mFonts.Add(glyphTypeface);
                return(mFonts.Count - 1);
            };

            ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size)
            {
                //RES_FONT_NO_TYPE_STYLE_COMBINATION
                //RES_FONT_INVALID_SIZE

                switch (_type)
                {
                case MoSync.Constants.FONT_TYPE_MONOSPACE:
                    break;

                case MoSync.Constants.FONT_TYPE_SERIF:
                    break;

                case MoSync.Constants.FONT_TYPE_SANS_SERIF:
                    break;

                default:
                    return(MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION);
                }

                return(0);
            };

            ioctls.maFontSetCurrent = delegate(int _font)
            {
                mCurrentFont       = mFonts[_font];
                mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont);
                return(0);
            };
        }
예제 #47
0
        public static XGlyphTypeface GetOrCreateFrom(string familyName, FontResolvingOptions fontResolvingOptions)
        {
            // Check cache for requested type face.
            string         typefaceKey = ComputeKey(familyName, fontResolvingOptions);
            XGlyphTypeface glyphTypeface;

            try
            {
                // Lock around TryGetGlyphTypeface and AddGlyphTypeface.
                Lock.EnterFontFactory();
                if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
                {
                    // Just return existing one.
                    return(glyphTypeface);
                }

                // Resolve typeface by FontFactory.
                FontResolverInfo fontResolverInfo = FontFactory.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey);
                if (fontResolverInfo == null)
                {
                    // No fallback - just stop.
                    throw new InvalidOperationException("No appropriate font found.");
                }

#if CORE && !WITHOUT_DRAWING || GDI
                GdiFont gdiFont = null;
#endif
#if WPF
                WpfFontFamily    wpfFontFamily    = null;
                WpfTypeface      wpfTypeface      = null;
                WpfGlyphTypeface wpfGlyphTypeface = null;
#endif
#if UWP
                // Nothing to do.
#endif
                // Now create the font family at the first.
                XFontFamily fontFamily;
#if !WITHOUT_DRAWING
                PlatformFontResolverInfo platformFontResolverInfo = fontResolverInfo as PlatformFontResolverInfo;
                if (platformFontResolverInfo != null)
                {
                    // Case: fontResolverInfo was created by platform font resolver
                    // and contains platform specific objects that are reused.
#if CORE || GDI
                    // Reuse GDI+ font from platform font resolver.
                    gdiFont    = platformFontResolverInfo.GdiFont;
                    fontFamily = XFontFamily.GetOrCreateFromGdi(gdiFont);
#endif
#if WPF
#if !SILVERLIGHT
                    // Reuse WPF font family created from platform font resolver.
                    wpfFontFamily    = platformFontResolverInfo.WpfFontFamily;
                    wpfTypeface      = platformFontResolverInfo.WpfTypeface;
                    wpfGlyphTypeface = platformFontResolverInfo.WpfGlyphTypeface;
                    fontFamily       = XFontFamily.GetOrCreateFromWpf(wpfFontFamily);
#else
                    fontFamily = XFontFamily.GetOrCreateFromWpf(new WpfFontFamily(familyName));
#endif
#endif
#if NETFX_CORE || UWP
                    fontFamily = null;
#endif
                }
                else
#endif
                {
                    // Case: fontResolverInfo was created by custom font resolver.

                    // Get or create font family for custom font resolver retrieved font source.
                    fontFamily = XFontFamily.GetOrCreateFontFamily(familyName);
                }

                // We have a valid font resolver info. That means we also have an XFontSource object loaded in the cache.
                XFontSource fontSource = FontFactory.GetFontSourceByFontName(fontResolverInfo.FaceName);
                Debug.Assert(fontSource != null);

                // Each font source already contains its OpenTypeFontface.

#if CORE || GDI
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations
#if !WITHOUT_DRAWING
                                                   , gdiFont
#endif
                                                   );
#endif
#if WPF
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, wpfTypeface, wpfGlyphTypeface);
#endif
#if NETFX_CORE || UWP
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations);
#endif
                GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface);
            }
            finally { Lock.ExitFontFactory(); }
            return(glyphTypeface);
        }
예제 #48
0
 internal WPFRenderer()
 {
     this.headerTextTypeface = unvell.ReoGrid.Rendering.PlatformUtility.GetFontDefaultTypeface(System.Windows.SystemFonts.SmallCaptionFontFamily);
 }