Beispiel #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);
        }
Beispiel #2
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            lock (_text)
            {
                if (RegularFont == null || FixedWidthFont == null) return;
                foreach (var at in _text)
                {

                    FontInfo f = RegularFont;
                    if (at.DisplayInfo.Font == ZFont.FIXED_WIDTH_FONT || at.DisplayInfo.ImplementsStyle(ZStyles.FIXED_WIDTH_STYLE))
                    {
                        f = FixedWidthFont;
                    }
                    Brush b = ZColorCheck.ZColorToBrush(at.DisplayInfo.ForegroundColor, Support.ColorType.Foreground);
                    FormattedText ft = new FormattedText(at.Text,
                        System.Globalization.CultureInfo.CurrentCulture,
                        FlowDirection.LeftToRight, f.Typeface, f.PointSize, b,
                        new NumberSubstitution(), TextFormattingMode.Display);

                    if (at.DisplayInfo.ImplementsStyle(ZStyles.REVERSE_STYLE))
                    {
                        drawingContext.DrawRectangle(b, null, new Rect(at.X + 2, at.Y + 2, ft.WidthIncludingTrailingWhitespace, Math.Max(ft.Height, FontHeight)));
                        ft.SetForegroundBrush(ZColorCheck.ZColorToBrush(at.DisplayInfo.BackgroundColor, Support.ColorType.Background));
                    }
                    drawingContext.DrawText(ft, new Point(at.X + 2, at.Y + 2));
                    // Note: Offsetting positions by 2 to get everything to line up correctly
                }
            }
        }
        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;            
        }
        private string GetTrimmedPath(double width)
        {
            string filename = System.IO.Path.GetFileName(Path);
            string directory = System.IO.Path.GetDirectoryName(Path);
            string drive = directory.Substring(0, directory.IndexOf(System.IO.Path.VolumeSeparatorChar) + 2);
            directory = directory.Substring(drive.Length);
            bool widthOk = false;
            bool changedWidth = false;

            do
            {
                var formatted = new FormattedText(
                    string.Format("{2}:\\...{0}\\{1}", directory, filename, drive),
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    FontFamily.GetTypefaces().First(),
                    FontSize,
                    Foreground
                    );

                widthOk = formatted.Width < width;

                if (!widthOk)
                {
                    changedWidth = true;
                    directory = directory.Substring(directory.IndexOf(System.IO.Path.VolumeSeparatorChar) + 2);

                    if (directory.Length == 0) return "...\\" + filename;
                }
            } while (!widthOk);

            if (!changedWidth)
                return Path;
            return string.Format("{2}...{0}\\{1}", directory, filename, drive);
        }
        protected override void DrawPointElement(DrawingContext dc, int Zoom)
        {
            if (Zoom > 12 || IsMouseOver)
            {
                string postLabelText = string.Format("{0}км", (double)Post.Ordinate / 1000);
                var postLabel = new FormattedText(postLabelText, CultureInfo.CurrentCulture,
                                                  FlowDirection.LeftToRight, new Typeface("Verdana"), 10, mainBrush);

                const int flagHeight = 22;
                dc.PushTransform(new TranslateTransform(0, -flagHeight));

                dc.DrawRectangle(Brushes.White, new Pen(mainBrush, 1), new Rect(-0.5, -0.5, Math.Round(postLabel.Width) + 5, Math.Round(postLabel.Height) + 2));
                dc.DrawText(postLabel, new Point(2, 0));
                dc.DrawLine(new Pen(mainBrush, 2), new Point(0, 0), new Point(0, flagHeight));

                dc.Pop();
            }

            if (Zoom > 8)
                dc.DrawEllipse(SectionBrush, new Pen(mainBrush, 1.5), new Point(0, 0), 5, 5);
            else
                dc.DrawRectangle(SectionBrush, null, new Rect(-2, -2, 4, 4));

            if (IsMouseOver)
            {
                dc.PushTransform(new TranslateTransform(3, 10));
                PrintStack(dc,
                           new FormattedText(Post.Direction == OrdinateDirection.Increasing ? "Возрастает по неч." : "Убывает по неч.",
                                             CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 10, Brushes.DarkBlue),
                           new FormattedText(String.Format("Пути: {0}", string.Join(", ", Post.Tracks.Select(TrackName))),
                                             CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 10, Brushes.DarkOliveGreen));
                dc.Pop();
            }
        }
Beispiel #6
0
        public ZTextBufferWindow(ZWindowManager manager, FontAndColorService fontAndColorService)
            : base(manager, fontAndColorService)
        {
            this.normalFontFamily = new FontFamily("Cambria");
            this.fixedFontFamily = new FontFamily("Consolas");

            var zero = new FormattedText(
                textToFormat: "0",
                culture: CultureInfo.InstalledUICulture,
                flowDirection: FlowDirection.LeftToRight,
                typeface: new Typeface(normalFontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
                emSize: this.FontSize,
                foreground: Brushes.Black);

            this.fontCharSize = new Size(zero.Width, zero.Height);

            this.document = new FlowDocument
            {
                FontFamily = normalFontFamily,
                FontSize = this.FontSize,
                PagePadding = new Thickness(8.0)
            };

            this.paragraph = new Paragraph();
            this.document.Blocks.Add(this.paragraph);

            this.scrollViewer = new FlowDocumentScrollViewer
            {
                FocusVisualStyle = null,
                Document = this.document
            };

            this.Children.Add(this.scrollViewer);
        }
Beispiel #7
0
        void BuildFaceModel( DrawingContext dc )
        {
            if ( produced ) {
                FormattedText completed_msg = new FormattedText( "Status : Completed", CultureInfo.GetCultureInfo( "ja-JP" ), FlowDirection.LeftToRight, new Typeface( "Georgia" ), 25, Brushes.Green );
                dc.DrawText( completed_msg, new Point( 50, 50 ) );
                return;
            }
            if ( faceModelBuilder == null ) {
                return;
            }
            FaceModelBuilderCollectionStatus collection;
            collection = faceModelBuilder.CollectionStatus;
            if ( collection == 0 ) {
                return;
            }
            //Collection Status
            FormattedText text = new FormattedText( "Status : " + collection.ToString(), CultureInfo.GetCultureInfo( "ja-JP" ), FlowDirection.LeftToRight, new Typeface( "Georgia" ), 25, Brushes.Green );
            dc.DrawText( text, new Point( 50, 50 ) );
            String status = status2string( collection );
            text = new FormattedText( status, CultureInfo.GetCultureInfo( "ja-JP" ), FlowDirection.LeftToRight, new Typeface( "Georgia" ), 25, Brushes.Green );
            dc.DrawText( text, new Point( 50, 80 ) );

            //Capture Status
            FaceModelBuilderCaptureStatus capture;
            capture = faceModelBuilder.CaptureStatus;
            if ( capture == 0 ) {
                return;
            }
            status = status2string( capture );
            text = new FormattedText( status, CultureInfo.GetCultureInfo( "ja-JP" ), FlowDirection.LeftToRight, new Typeface( "Georgia" ), 25, Brushes.Green );
            dc.DrawText( text, new Point( 50, 110 ) );
            return;
        }
Beispiel #8
0
        /// <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);
        }
Beispiel #9
0
        public void Rebuild()
        {
            needsRebuild = false;
            var dir = System.Windows.FlowDirection.LeftToRight;

            formattedText = new System.Windows.Media.FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, dir, defaultFont, 36, brush);
            if (width > 0)
            {
                formattedText.MaxTextWidth = width;
            }
            if (height > 0)
            {
                formattedText.MaxTextHeight = height;
            }
            if (Font != null)
            {
                ApplyFont();
            }
            if (textTrimming != null)
            {
                ApplyTrimming();
            }

            if (attributes != null)
            {
                foreach (var at in attributes)
                {
                    ApplyAttribute(at);
                }
            }
        }
        public FleetRender( Fleet fleet, bool? lines )
        {
            LineGeometry line;
            FormattedText text;
            Geometry textGeom;

            double x = fleet.SourcePlanet.X +
                       ((fleet.DestinationPlanet.X - fleet.SourcePlanet.X) *
                        ((double)(fleet.TotalTripLength - fleet.TurnsRemaining) / fleet.TotalTripLength));
            double y = fleet.SourcePlanet.Y +
                       ((fleet.DestinationPlanet.Y - fleet.SourcePlanet.Y) *
                        ((double)(fleet.TotalTripLength - fleet.TurnsRemaining) / fleet.TotalTripLength));

            if (lines ?? false)
            {
                line = new LineGeometry(new Point(x, y), new Point(fleet.DestinationPlanet.X, fleet.DestinationPlanet.Y));
                m_gg.Children.Add(line);
            }

            text = new FormattedText(
                fleet.ShipCount.ToString(),
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface("Tahoma"),
                0.8,
                Brushes.Black);
            textGeom = text.BuildGeometry(new Point(x - text.Width / 2, y - text.Height / 2));
            m_gg.Children.Add(textGeom);

            m_gg.Freeze();
        }
Beispiel #11
0
 private void DrawBar(DrawingContext drawingContext, int row, int column, FormattedText font)
 {
     drawingContext.DrawLine(
         new Pen(Foreground, 2),
         new Point(column * font.Width, row * font.Height),
         new Point(column * font.Width, (row + 1) * font.Height));
 }
        public override void Render(DrawingContext dc, Point screenPoint)
        {
            Point dataPoint = screenPoint.ScreenToData(this.ct.Transform);
            Point dataPointZero = new Point(dataPoint.X,0.0);
            Point screenPointZero = dataPointZero.DataToScreen(this.ct.Transform);
            //const double verticalShift = 5; // px

            //dc.DrawLine(new Pen(Brushes.Black, 1), Point.Add(screenPoint, new Vector(0, 40)), screenPoint);

            double pointx = screenPointZero.X + 2;
            double pointy = screenPointZero.Y + 2;

            FormattedText textToDraw = new FormattedText(dataPoint.Y.ToString("0.000"), Thread.CurrentThread.CurrentCulture,
                   FlowDirection.LeftToRight, new Typeface("Arial"), 12, Brushes.Black);
            dc.DrawText(textToDraw, new Point(pointx, pointy));

            /*
            string svalue = dataPoint.Y.ToString("0.000");
            foreach (var s in svalue)
            {
                if (s.Equals('.'))
                    continue;
                FormattedText textToDraw = new FormattedText(s.ToString(), Thread.CurrentThread.CurrentCulture,
                    FlowDirection.LeftToRight, new Typeface("Arial"), 12, Brushes.Black);
                dc.DrawText(textToDraw, new Point(pointx,pointy));
                pointy = pointy + 10;

            }
             * */
        }
        /// <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;
        }
Beispiel #14
0
        /// <summary>
        /// any custom drawing here
        /// </summary>
        /// <param name="drawingContext"></param>
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            if (selectedDirection != null && hasDirection == true)
            {
                //start = DateTime.Now;



                //end = DateTime.Now;
                //delta = (int)(end - start).TotalMilliseconds;

                //FormattedText text = new FormattedText(string.Format(CultureInfo.InvariantCulture, "{0:0.0}", Zoom) + "z, " + MapProvider + ", refresh: " + counter++ + ", load: " + ElapsedMilliseconds + "ms, render: " + delta + "ms", CultureInfo.InvariantCulture, fd, tf, 20, Brushes.Blue);
                //drawingContext.DrawText(text, new Point(text.Height, text.Height));
                //text = null;


                SolidColorBrush brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF072527"));
                FormattedText text = new FormattedText("End location: " + selectedDirection.EndAddress + ".\nStart location: " + selectedDirection.StartAddress + ".\nDistance: " + selectedDirection.Distance + ", duration: " + selectedDirection.Duration, CultureInfo.InvariantCulture, fd, tf, 20, brush);

                SolidColorBrush boxy = new SolidColorBrush(Color.FromArgb(130, 180, 180, 180));
                drawingContext.DrawRectangle(boxy, new Pen(), new Rect(new Point(text.Height, text.Height), new Point(text.Height + text.Width, text.Height * 2)));


                drawingContext.DrawText(text, new Point(text.Height, text.Height));

                text = null;
            }
        }
        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;
        }
Beispiel #16
0
        internal void Update(
            string text,
            ITextViewLine line,
            IWpfTextView view,
            TextRunProperties formatting,
            double marginWidth,
            double verticalOffset)
        {
            LineTag = line.IdentityTag;

            if (_text == null || !string.Equals(_text, text, StringComparison.Ordinal))
            {
                _text = text;
                _formattedText = new FormattedText(
                    _text,
                    CultureInfo.InvariantCulture,
                    FlowDirection.LeftToRight,
                    formatting.Typeface,
                    formatting.FontRenderingEmSize,
                    formatting.ForegroundBrush);

                _horizontalOffset = Math.Round(marginWidth - _formattedText.Width);
                InvalidateVisual();
            }

            var num = line.TextTop - view.ViewportTop + verticalOffset;
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (num == _verticalOffset) return;
            _verticalOffset = num;
            InvalidateVisual();
        }
Beispiel #17
0
        private void DrawFormattedTextCore(SystemMedia.FormattedText formattedText, Vector2D origin, double angle = 0)
        {
            var originScreenPoint       = _canvasProxy.ToScreen(origin);
            var nativeOriginScreenPoint = Vector2DAdapter.ConvertToSystemPoint(originScreenPoint);

            //若偏转角度数不为圆周整数整除,则应用偏转角变化;
            if (angle % Math.PI * 2 != 0)
            {
                var rotateTransform = new SystemMedia.RotateTransform {
                    Angle = Extension.RadToDeg(angle),

                    CenterX = nativeOriginScreenPoint.X,
                    CenterY = nativeOriginScreenPoint.Y
                };

                //推入;
                DrawingContext.PushTransform(rotateTransform);

                DrawingContext.DrawText(formattedText, nativeOriginScreenPoint);

                //出栈;
                DrawingContext.Pop();
            }
            else
            {
                DrawingContext.DrawText(formattedText, nativeOriginScreenPoint);
            }
        }
        private void escribeTexto()
        {
            string texto = "";
            FormattedText frmTxt = new FormattedText(texto,
                 CultureInfo.GetCultureInfo("en-us"),
            FlowDirection.LeftToRight, new Typeface("Verdana"), 32, Brushes.Black);
            // Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
            frmTxt.MaxTextWidth = 300;
            frmTxt.MaxTextHeight = 240;

            // Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
            // The font size is calculated in terms of points -- not as device-independent pixels.
            frmTxt.SetFontSize(36 * (96.0 / 72.0), 0, 5);

            // Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
            frmTxt.SetFontWeight(FontWeights.Bold, 6, 11);

            // Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
            frmTxt.SetForegroundBrush(
                                    new LinearGradientBrush(
                                    Colors.Orange,
                                    Colors.Teal,
                                    90.0),
                                    6, 11);

            // Use an Italic font style beginning at the 28th character and continuing for 28 characters.
            frmTxt.SetFontStyle(FontStyles.Italic, 28, 28);

            //// Draw the formatted text string to the DrawingContext of the control.
            //drawingContext.DrawText(frmTxt, new Point(10, 0));
        }
        protected override void OnRender(DrawingContext dc)
        {

            Size size = new Size(base.ActualWidth, base.ActualHeight);
            int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) + 1;
            if ((this.Maximum - this.Minimum) % this.TickFrequency == 0)
                tickCount -= 1;
            Double tickFrequencySize;
            // Calculate tick's setting
            tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
            string text = "";
            FormattedText formattedText = null;
            double num = this.Maximum - this.Minimum;
            int i = 0;
            // Draw each tick text
            for (i = 0; i <= tickCount; i++)
            {
                text = Convert.ToString(Convert.ToInt32(this.Minimum + this.TickFrequency * i), 10);
                //g.DrawString(text, font, brush, drawRect.Left + tickFrequencySize * i, drawRect.Top + drawRect.Height/2, stringFormat);

                formattedText = new FormattedText(text, CultureInfo.GetCultureInfo("ru-Ru"), FlowDirection.LeftToRight, new Typeface("Arial"), 8, Brushes.Black);
                dc.DrawText(formattedText, new Point((tickFrequencySize * i), 30));

            }
        }
Beispiel #20
0
        public static SystemMedia.FormattedText ConvertToSystemFormattedText(FormattedText formattedText)
        {
            if (formattedText == null)
            {
                throw new ArgumentNullException(nameof(formattedText));
            }

            var brush = BrushAdapter.ConvertToSystemBrush(formattedText.ForegroundBlocks.FirstOrDefault()?.Brush);
            var ft    = new SystemMedia.FormattedText(
                formattedText.Text,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                _typeFace,
                formattedText.FontSize,
                brush
                );

            if (formattedText.ForegroundBlocks != null)
            {
                foreach (var item in formattedText.ForegroundBlocks)
                {
                    ft.SetForegroundBrush(BrushAdapter.ConvertToSystemBrush(item.Brush), item.Start, item.Length);
                }
            }

            return(ft);
        }
        private string GetTrimmedPath(double width)
        {
            if (string.IsNullOrWhiteSpace(Path))
                return string.Empty;

            var filename = System.IO.Path.GetFileName(Path);
            var directory = System.IO.Path.GetDirectoryName(Path);
            bool widthOK;
            var changedWidth = false;

            do
            {
                FormattedText formatted = new FormattedText(
                    string.Format("{0}...\\{1}", directory, filename),
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    FontFamily.GetTypefaces().First(),
                    FontSize,
                    Foreground);

                widthOK = formatted.Width < (width * 0.95);

                if (widthOK) continue;

                changedWidth = true;
                if (directory == null) return "...\\" + filename;

                directory = directory.Substring(0, directory.Length - 1);
                if (directory.Length == 0) return "...\\" + filename;
            } while (!widthOK);

            return !changedWidth ? Path : string.Format("{0}...{1}", directory, filename);
        }
		public static FormattedText CreateFormattedText(ExportText exportText)
		{
			FlowDirection flowDirection;
			
			var culture = CultureInfo.CurrentCulture;
			if (culture.TextInfo.IsRightToLeft) {
				flowDirection = FlowDirection.RightToLeft;
			} else {
				flowDirection = FlowDirection.LeftToRight;
			}
			
			var emSize = ExtensionMethodes.ToPoints((int)exportText.Font.SizeInPoints +1);
			
			var formattedText = new FormattedText(exportText.Text,
				CultureInfo.CurrentCulture,
				flowDirection,
				new Typeface(exportText.Font.FontFamily.Name),
				emSize,
				new SolidColorBrush(exportText.ForeColor.ToWpf()), null, TextFormattingMode.Display);
			
			formattedText.MaxTextWidth = ExtensionMethodes.ToPoints(exportText.DesiredSize.Width);
			
			ApplyPrintStyles(formattedText,exportText);

			return formattedText;
		}
Beispiel #23
0
        /// <summary>
        /// Store <paramref name="timeStamp"/> and updates the text for the visual.
        /// </summary>
        /// <param name="timeStamp">Time of the event.</param>
        /// <param name="line">The line that this time stamp corresponds to.</param>
        /// <param name="view">The <see cref="IWpfTextView"/> to whom the <paramref name="line"/> belongs.</param>
        /// <param name="formatting">Properties for the time stamp text.</param>
        /// <param name="marginWidth">Used to calculate the horizontal offset for <see cref="OnRender(DrawingContext)"/>.</param>
        /// <param name="verticalOffset">Used to calculate the vertical offset for <see cref="OnRender(DrawingContext)"/>.</param>
        /// <param name="showHours">Option to show hours on the time stamp.</param>
        /// <param name="showMilliseconds">Option to show milliseconds on the time stamp.</param>
        internal void UpdateVisual(DateTime timeStamp, ITextViewLine line, IWpfTextView view, TextRunProperties formatting, double marginWidth, double verticalOffset,
                                   bool showHours, bool showMilliseconds)
        {
            this.LineTag = line.IdentityTag;

            if (timeStamp != this.TimeStamp)
            {
                this.TimeStamp = timeStamp;
                string text = GetFormattedTime(timeStamp, showHours, showMilliseconds);
                TextFormattingMode textFormattingMode = view.FormattedLineSource.UseDisplayMode ? TextFormattingMode.Display : TextFormattingMode.Ideal;
                _text = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
                                          formatting.Typeface, formatting.FontRenderingEmSize, formatting.ForegroundBrush,
                                          InvariantNumberSubstitution, textFormattingMode);

                _horizontalOffset = Math.Round(marginWidth - _text.Width);
                this.InvalidateVisual(); // force redraw
            }

            double newVerticalOffset = line.TextTop - view.ViewportTop + verticalOffset;
            if (newVerticalOffset != _verticalOffset)
            {
                _verticalOffset = newVerticalOffset;
                this.InvalidateVisual(); // force redraw
            }
        }
Beispiel #24
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            const int TextFontSize = 30;

               // Make a System.Windows.Media.FormattedText object.
            FormattedText text = new FormattedText("Hello Visual Layer!",
                    new System.Globalization.CultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface(this.FontFamily, FontStyles.Italic,
                        FontWeights.DemiBold, FontStretches.UltraExpanded),
                    TextFontSize,
                    Brushes.Green);

            // Create a DrawingVisual, and obtain the DrawingContext.
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                // Now, call any of the methods of DrawingContext to render data.
                drawingContext.DrawRoundedRectangle(Brushes.Yellow, new Pen(Brushes.Black, 5),
                  new Rect(5, 5, 450, 100), 20, 20);
                drawingContext.DrawText(text, new Point(20, 20));
            }

            // Dynamically make a bitmap, using the data in the DrawingVisual.
            RenderTargetBitmap bmp = new RenderTargetBitmap(500, 100, 100, 90, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);

            // Set the source of the Image control!
            myImage.Source = bmp;
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _processor = new SettingsProcessor();
            _processor.MoviePathsWorkComplete += delegate
            {
                double width = 0;
                double newWidth = 0;

                listBoxMovieLocations.Items.Clear();
                _processor.MoviePaths.ForEach(x =>
                    {
                        newWidth = new FormattedText(x.ConfigValue, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 32, Brushes.Black).Width;
                        if (newWidth > width)
                            width = newWidth;
                        listBoxMovieLocations.Items.Add(x.ConfigValue);
                        newWidth = 0;
                    });
                if (width != 0)
                    listBoxMovieLocations.Width = width;
            };

            if (System.Configuration.ConfigurationSettings.AppSettings.AllKeys.ToList().Find(x => x == "OnlineMode") != null)
            {
                if (System.Configuration.ConfigurationSettings.AppSettings.Get("OnlineMode") == "1")
                    checkBoxOnlineMode.IsChecked = true;
                else
                    checkBoxOnlineMode.IsChecked = false;
            }
        }
Beispiel #26
0
        public void Rebuild(string newText = null, bool keepWidth = true, bool keepHeight = true)
        {
            var font = new Typeface("Verdana");
            var dir  = System.Windows.FlowDirection.LeftToRight;
            var old  = formattedText;

            if (old != null && old.Text != null && newText == null)
            {
                newText = old.Text;
            }
            formattedText = new System.Windows.Media.FormattedText(newText ?? "", System.Globalization.CultureInfo.CurrentCulture, dir, font, 36, System.Windows.Media.Brushes.Black);
            if (old != null)
            {
                if (old.MaxTextWidth != 0 && keepWidth)
                {
                    formattedText.MaxTextWidth = old.MaxTextWidth;
                }
                if (old.MaxTextHeight != 0 && keepHeight)
                {
                    formattedText.MaxTextHeight = old.MaxTextHeight;
                }
            }
            if (Font != null)
            {
                SetFont(Font);
            }
        }
Beispiel #27
0
        private void DrawFormattedText(DpiScaleInfo dpiInfo)
        {
            FormattedText formattedText = new FormattedText(
                "FABLE",
                new System.Globalization.CultureInfo("en-US"),
                FlowDirection.LeftToRight,
                new Typeface(
                    new System.Windows.Media.FontFamily("Segoe UI"),
                    FontStyles.Normal,
                    FontWeights.Bold,
                    FontStretches.Normal),
                120,
                System.Windows.Media.Brushes.Red,
                dpiInfo.PixelsPerDip);

            // Build a geometry out of the text.
            Geometry geometry = new PathGeometry();
            geometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));

            // Adjust the geometry to fit the aspect ration of the video by scaling it.
            ScaleTransform myScaleTransform = new ScaleTransform();
            myScaleTransform.ScaleX = .85;
            myScaleTransform.ScaleY = 2.0;
            geometry.Transform = myScaleTransform;

            // Flatten the geometry and create a PathGeometry out of it.
            PathGeometry pathGeometry = new PathGeometry();
            pathGeometry = geometry.GetFlattenedPathGeometry();

            // Use the PathGeometry for the empty placeholder Path element in XAML.
            path.Data = pathGeometry;

            // Use the PathGeometry for the animated ball that follows the path of the text outline.
            matrixAnimation.PathGeometry = pathGeometry;
        }
        /// <summary>
        /// Creates a new System.Windows.Media.ImageSource of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush.
        /// </summary>
        /// <param name="icon">The FontAwesome icon to be drawn.</param>
        /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param>
        /// <returns>A new System.Windows.Media.ImageSource</returns>

        public static System.Windows.Media.ImageSource GetImageSource(int icon, System.Windows.Media.Brush foregroundBrush, double emSize = 100, double margin = 0)
        {
            string charIcon = char.ConvertFromUtf32(icon);

            if (_Typeface == null)
            {
                _Typeface = new System.Windows.Media.Typeface(FontFamily, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, System.Windows.FontStretches.Normal);
            }
            ;

            System.Windows.Media.DrawingVisual visual = new System.Windows.Media.DrawingVisual();

            using (System.Windows.Media.DrawingContext drawingContext = visual.RenderOpen())
            {
                FormattedText ft = new System.Windows.Media.FormattedText(
                    charIcon,
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Windows.FlowDirection.LeftToRight,
                    _Typeface, emSize - (2 * margin), foregroundBrush);

                ft.TextAlignment = System.Windows.TextAlignment.Center;

                drawingContext.DrawRectangle(null, new Pen(Brushes.Black, 0), new System.Windows.Rect(0, 0, emSize, emSize));
                drawingContext.DrawText(ft, new System.Windows.Point(emSize / 2, margin));
            };

            return(new System.Windows.Media.DrawingImage(visual.Drawing));
        }
Beispiel #29
0
        private void CaculateFirstMaker(Size size)
        {
            Marker mk = new Marker();
            Point startp = new Point();

            startp.X = ChartPropery.AxisLineMargin - ChartPropery.MarkerHeight;
            startp.Y = size.Height - ChartPropery.AxisLineMargin-1;

            Point endp = new Point();
            endp.X = ChartPropery.AxisLineMargin;
            endp.Y = startp.Y;

            mk.StartPoint = startp;
            mk.EndPoint = endp;

            FormattedText formattedText = new FormattedText(MinValue.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 10,
            Brushes.White);
            mk.Value = formattedText;

            Point tpoint = new Point();
            tpoint.X = ChartPropery.AxisLineMargin - formattedText.Width - ChartPropery.MarkerHeight;
            tpoint.Y = endp.Y - formattedText.Height;
            mk.TextPoint = tpoint;
            _Markers.Add(mk);
        }
Beispiel #30
0
        private static Point GetTextOrigin(ShapeStyle style, ref Rect rect, FormattedText ft)
        {
            double ox, oy;

            switch (style.TextStyle.TextHAlignment)
            {
                case TextHAlignment.Left:
                    ox = rect.TopLeft.X;
                    break;
                case TextHAlignment.Right:
                    ox = rect.Right - ft.Width;
                    break;
                case TextHAlignment.Center:
                default:
                    ox = (rect.Left + rect.Width / 2.0) - (ft.Width / 2.0);
                    break;
            }

            switch (style.TextStyle.TextVAlignment)
            {
                case TextVAlignment.Top:
                    oy = rect.TopLeft.Y;
                    break;
                case TextVAlignment.Bottom:
                    oy = rect.Bottom - ft.Height;
                    break;
                case TextVAlignment.Center:
                default:
                    oy = (rect.Bottom - rect.Height / 2.0) - (ft.Height / 2.0);
                    break;
            }

            return new Point(ox, oy);
        }
Beispiel #31
0
        /// <summary>
        /// Create the outline geometry based on the formatted text.
        /// </summary>
        public void CreateText()
        {
            FontStyle fontStyle = FontStyles.Normal;
            FontWeight fontWeight = FontWeights.Medium;

            if (Bold == true) fontWeight = FontWeights.Bold;
            if (Italic == true) fontStyle = FontStyles.Italic;

            // Create the formatted text based on the properties set.
            FormattedText formattedText = new FormattedText(
                Text,
                CultureInfo.GetCultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(Font, fontStyle, fontWeight, FontStretches.Normal),
                FontSize,
                Brushes.Black // This brush does not matter since we use the geometry of the text. 
                );

            // Build the geometry object that represents the text.
            _textGeometry = formattedText.BuildGeometry(new Point(0, 0));




            //set the size of the custome control based on the size of the text
            this.MinWidth = formattedText.Width;
            this.MinHeight = formattedText.Height;

        }
Beispiel #32
0
        /// <summary>
        /// Create the outline geometry based on the formatted text.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="bold"></param>
        /// <param name="italic"></param>
        /// <param name="family"></param>
        /// <param name="size"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        private PathGeometry CreateText(string text, bool bold, bool italic, FontFamily family, double size, System.Windows.Point location)
        {
            System.Windows.FontStyle fontStyle = FontStyles.Normal;
            FontWeight fontWeight = FontWeights.Medium;

            if (bold == true)
            {
                fontWeight = FontWeights.Bold;
            }

            if (italic == true)
            {
                fontStyle = FontStyles.Italic;
            }

            System.Windows.Media.FormattedText formattedText = new System.Windows.Media.FormattedText(
                text,
                System.Globalization.CultureInfo.GetCultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(family, fontStyle, fontWeight, FontStretches.Normal),
                size, System.Windows.Media.Brushes.Black
                );

            Geometry textGeometry = formattedText.BuildGeometry(location);

            return(textGeometry.GetFlattenedPathGeometry());
        }
        public int Highlight(FormattedText text, int previousBlockCode)
        {
            // WORDS RULES
            Regex wordsRgx = new Regex("[a-zA-Z_][a-zA-Z0-9_]*");
            foreach (Match m in wordsRgx.Matches(text.Text))
            {
                foreach (HighlightWordsRule rule in WordsRules)
                {
                    if (rule.Expression.IsMatch(m.Value))
                    {
                        ApplyFormat(text, rule.Options, m.Index, m.Length);
                    }
                }
            }
            // REGEX RULES
            foreach (AdvancedHighlightRule rule in RegexRules)
            {
                foreach (Match m in rule.Satisfies(text.Text))
                {
                    ApplyFormat(text, rule.Options, m.Index, m.Length);
                }
            }
            // LINES RULES
            foreach (HighlightLineRule rule in LineRules)
            {
                foreach (Match m in rule.Satisfies(text.Text))
                {
                    ApplyFormat(text, rule.Options, m.Index, m.Length);
                }
            }

            return -1;
        }
Beispiel #34
0
        protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
        {
            double        fontSize;
            Typeface      typeFace;
            TextAlignment alignment;
            FlowDirection flowDirection;
            double        padding;

            if (AdornedPasswordBox != null)
            {
                alignment     = ConvertAlignment(AdornedPasswordBox.HorizontalContentAlignment);
                flowDirection = AdornedPasswordBox.FlowDirection;
                fontSize      = AdornedPasswordBox.FontSize;
                typeFace      = AdornedPasswordBox.FontFamily.GetTypefaces().FirstOrDefault();
                padding       = 6;
            }
            else
            {
                alignment     = AdornedTextBox.ReadLocalValue(TextBox.TextAlignmentProperty) != DependencyProperty.UnsetValue ? AdornedTextBox.TextAlignment : ConvertAlignment(AdornedTextBox.HorizontalContentAlignment);
                flowDirection = AdornedTextBox.FlowDirection;
                fontSize      = AdornedTextBox.FontSize;
                typeFace      = AdornedTextBox.FontFamily.GetTypefaces().FirstOrDefault();
                padding       = 6;
            }
            var text = new System.Windows.Media.FormattedText(PlaceholderText ?? "", CultureInfo.CurrentCulture, flowDirection, typeFace, fontSize, System.Windows.Media.Brushes.LightGray)
            {
                TextAlignment = alignment
            };

            drawingContext.DrawText(text, new System.Windows.Point(padding, (RenderSize.Height - text.Height) / 2));
        }
Beispiel #35
0
 /// <inheritdoc/>
 public override VisualLineElement ConstructElement(int offset)
 {
     if (FoldingManager == null)
         return null;
     int foldedUntil = -1;
     string title = null;
     foreach (FoldingSection fs in FoldingManager.GetFoldingsAt(offset)) {
         if (fs.IsFolded) {
             if (fs.EndOffset > foldedUntil) {
                 foldedUntil = fs.EndOffset;
                 title = fs.Title;
             }
         }
     }
     if (foldedUntil > offset) {
         if (string.IsNullOrEmpty(title))
             title = "...";
         FormattedText text = new FormattedText(
             title,
             CurrentContext.GlobalTextRunProperties.CultureInfo,
             FlowDirection.LeftToRight,
             CurrentContext.GlobalTextRunProperties.Typeface,
             CurrentContext.GlobalTextRunProperties.FontRenderingEmSize,
             Brushes.Gray
         );
         return new FoldingLineElement(text, foldedUntil - offset);
     } else {
         return null;
     }
 }
Beispiel #36
0
        protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
        {
            double fontSize;
            Typeface typeFace;
            TextAlignment alignment;
            FlowDirection flowDirection;
            double padding;
            if (AdornedPasswordBox != null) {
                alignment = ConvertAlignment (AdornedPasswordBox.HorizontalContentAlignment);
                flowDirection = AdornedPasswordBox.FlowDirection;
                fontSize = AdornedPasswordBox.FontSize;
                typeFace = AdornedPasswordBox.FontFamily.GetTypefaces ().FirstOrDefault ();
                padding = 6;
            }
            else {
                alignment = AdornedTextBox.ReadLocalValue (TextBox.TextAlignmentProperty) !=DependencyProperty.UnsetValue ? AdornedTextBox.TextAlignment : ConvertAlignment (AdornedTextBox.HorizontalContentAlignment);
                flowDirection = AdornedTextBox.FlowDirection;
                fontSize = AdornedTextBox.FontSize;
                typeFace = AdornedTextBox.FontFamily.GetTypefaces ().FirstOrDefault ();
                padding = 6;
            }
            var text = new System.Windows.Media.FormattedText (PlaceholderText ?? "", CultureInfo.CurrentCulture, flowDirection, typeFace, fontSize, System.Windows.Media.Brushes.LightGray) {
                TextAlignment = alignment
            };

            drawingContext.DrawText (text, new System.Windows.Point (padding, (RenderSize.Height - text.Height) / 2));
        }
Beispiel #37
0
 /// <inheritdoc/>
 public override VisualLineElement ConstructElement(int offset)
 {
     string newlineText;
     DocumentLine lastDocumentLine = CurrentContext.VisualLine.LastDocumentLine;
     if (lastDocumentLine.DelimiterLength == 2) {
         newlineText = "\u00B6";
     } else if (lastDocumentLine.DelimiterLength == 1) {
         char newlineChar = CurrentContext.Document.GetCharAt(lastDocumentLine.Offset + lastDocumentLine.Length);
         if (newlineChar == '\r')
             newlineText = "\\r";
         else if (newlineChar == '\n')
             newlineText = "\\n";
         else
             newlineText = "?";
     } else {
         return null;
     }
     FormattedText text = new FormattedText(
         newlineText,
         CurrentContext.GlobalTextRunProperties.CultureInfo,
         FlowDirection.LeftToRight,
         CurrentContext.GlobalTextRunProperties.Typeface,
         CurrentContext.GlobalTextRunProperties.FontRenderingEmSize,
         Brushes.LightGray
     );
     return new NewLineTextElement(text);
 }
Beispiel #38
0
 public void Highlight(FormattedText text)
 {
     foreach (var item in Rules)
     {
         item.Highlight(text);
     }
 }
Beispiel #39
0
        public SizeF MeasureString(Font font, string text)
        {
            var fontHandler   = font.Handler as FontHandler;
            var brush         = new swm.SolidColorBrush(swm.Colors.White);
            var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.Typeface, fontHandler.PixelSize, brush);

            return(new SizeF((float)formattedText.WidthIncludingTrailingWhitespace, (float)formattedText.Height));
        }
Beispiel #40
0
        public void DrawText(Font font, Color color, int x, int y, string text)
        {
            var fontHandler   = font.Handler as FontHandler;
            var brush         = new swm.SolidColorBrush(Generator.Convert(color));
            var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.Typeface, fontHandler.PixelSize, brush);

            Control.DrawText(formattedText, new sw.Point(x, y));
        }
Beispiel #41
0
 public void Apply(swm.FormattedText control)
 {
     control.SetFontFamily(WpfFamily);
     control.SetFontStyle(WpfFontStyle);
     control.SetFontStretch(WpfFontStretch);
     control.SetFontWeight(WpfFontWeight);
     control.SetFontSize(WpfSize);
     control.SetTextDecorations(WpfTextDecorationsFrozen);
 }
Beispiel #42
0
        private void RenderException(Exception exception, DrawingContext drawingContext)
        {
            var textToFormat  = $"XAML load error in {Source}: {exception}";
            var formattedText = new System.Windows.Media.FormattedText(textToFormat, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(SystemFonts.MenuFontFamily.Source), FontSize, Brushes.Red, new NumberSubstitution(), TextFormattingMode.Display, 96);

            formattedText.MaxTextWidth = ActualWidth;

            drawingContext.DrawText(formattedText, new System.Windows.Point((ActualWidth - formattedText.Width) / 2, (ActualHeight - formattedText.Height) / 2));
        }
Beispiel #43
0
        public void DrawHeaderText(string text, Brush brush, Rectangle rect)
        {
            var ft = new System.Windows.Media.FormattedText(text,
                                                            System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
                                                            this.headerTextTypeface, headerTextScale / 72f * 96f, brush);

            base.PlatformGraphics.DrawText(ft,
                                           new Point(rect.X + (rect.Width - ft.Width) / 2, rect.Y + (rect.Height - ft.Height) / 2));
        }
Beispiel #44
0
        public SizeF MeasureString(string text)
        {
            if (measureBrush == null)
            {
                measureBrush = new swm.SolidColorBrush(swm.Colors.White);
            }
            var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, WpfTypeface, PixelSize, measureBrush);

            return(new SizeF((float)formattedText.WidthIncludingTrailingWhitespace, (float)formattedText.Height));
        }
Beispiel #45
0
        public SizeF MeasureString(string text)
        {
            if (measureBrush == null)
            {
                measureBrush = new swm.SolidColorBrush(swm.Colors.White);
            }
#pragma warning disable CS0618 // 'FormattedText.FormattedText(string, CultureInfo, FlowDirection, Typeface, double, Brush)' is obsolete: 'Use the PixelsPerDip override'
            var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, WpfTypeface, WpfSize, measureBrush);
#pragma warning restore CS0618 // Type or member is obsolete
            return(new SizeF((float)formattedText.WidthIncludingTrailingWhitespace, (float)formattedText.Height));
        }
Beispiel #46
0
        public void DrawText(Font font, SolidBrush b, float x, float y, string text)
        {
            var fontHandler = font.Handler as FontHandler;

            if (fontHandler != null)
            {
                var brush         = new swm.SolidColorBrush(b.Color.ToWpf());           // BUGBUG: FIX
                var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.PixelSize, brush);
                Control.DrawText(formattedText, new sw.Point(x, y));
            }
        }
Beispiel #47
0
 public static Font SetEtoFont(this swm.FormattedText control, Font font)
 {
     if (control == null)
     {
         return(font);
     }
     if (font != null)
     {
         ((FontHandler)font.Handler).Apply(control);
     }
     return(font);
 }
        public static Size MeasureString(this TextBlock textBlock)
        {
            var formattedText = new Media.FormattedText(
                textBlock.Text,
                CultureInfo.CurrentUICulture,
                FlowDirection.LeftToRight,
                new Media.Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
                textBlock.FontSize,
                Media.Brushes.Black);

            return(new Size(formattedText.Width + textBlock.Padding.Left + textBlock.Padding.Right, formattedText.Height + textBlock.Padding.Top + textBlock.Padding.Bottom));
        }
Beispiel #49
0
        private void SetTextWidth()
        {
            var formattedText = new System.Windows.Media.FormattedText(
                DisplayName,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                TEXT_FONT,
                15.5,
                Brushes.Black);

            TextWidth = formattedText.Width + 20;
        }
Beispiel #50
0
        //public TextBlock GetHeaderText()
        //{
        //    var c = GetTemplateChild("PART_Content") as System.Windows.Controls.ContentPresenter;
        //    if (c != null)
        //    {
        //        var t = c.Content as TextBlock;
        //        return t;
        //    }
        //    return null;
        //}

        public double GetItemFullWidth()
        {
            double itemWidth = 0;
            var    iconPart  = GetTemplateChild("PART_Icon") as System.Windows.FrameworkElement;

            if (iconPart != null)
            {
                itemWidth += iconPart.Width;
            }
            var closePart = GetTemplateChild("PART_Close") as System.Windows.FrameworkElement;

            if (closePart != null)
            {
                itemWidth += closePart.Width;
            }
            var contentPart = GetTemplateChild("PART_Content") as System.Windows.Controls.ContentPresenter;

            if (contentPart != null)
            {
                var headerText = contentPart.Content as TextBlock;
                if (headerText != null)
                {
                    var formattedText = new System.Windows.Media.FormattedText(
                        headerText.Text,
                        System.Globalization.CultureInfo.CurrentCulture,
                        headerText.FlowDirection,
                        new System.Windows.Media.Typeface(headerText.FontFamily, headerText.FontStyle, headerText.FontWeight, headerText.FontStretch),
                        headerText.FontSize,
                        headerText.Foreground);
                    itemWidth += formattedText.Width;
                }
                else
                {
                    itemWidth += contentPart.Width;
                }
            }
            itemWidth += 15;

            return(itemWidth);

            //if (headerText != null && iconPart != null && closePart != null)
            //{
            //    var formattedText = new System.Windows.Media.FormattedText(
            //                            headerText.Text,
            //                            System.Globalization.CultureInfo.CurrentCulture,
            //                            headerText.FlowDirection,
            //                            new System.Windows.Media.Typeface(headerText.FontFamily, headerText.FontStyle, headerText.FontWeight, headerText.FontStretch),
            //                            headerText.FontSize,
            //                            headerText.Foreground);
            //    return formattedText.Width + iconPart.Width + closePart.Width + 8;
            //}
            //return Width;
        }
        protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
        {
            double        fontSize;
            Typeface      typeFace;
            TextAlignment alignment;
            FlowDirection flowDirection;
            bool          multiline = false;
            double        ypos = 3, xpos = 6;

            if (AdornedPasswordBox != null)
            {
                alignment     = ConvertAlignment(AdornedPasswordBox.HorizontalContentAlignment);
                flowDirection = AdornedPasswordBox.FlowDirection;
                fontSize      = AdornedPasswordBox.FontSize;
                typeFace      = AdornedPasswordBox.FontFamily.GetTypefaces().FirstOrDefault();
            }
            else if (AdornedTextBox != null)
            {
                multiline     = AdornedTextBox.AcceptsReturn;
                alignment     = AdornedTextBox.ReadLocalValue(TextBox.TextAlignmentProperty) != DependencyProperty.UnsetValue ? AdornedTextBox.TextAlignment : ConvertAlignment(AdornedTextBox.HorizontalContentAlignment);
                flowDirection = AdornedTextBox.FlowDirection;
                fontSize      = AdornedTextBox.FontSize;
                typeFace      = AdornedTextBox.FontFamily.GetTypefaces().FirstOrDefault();
            }
            else
            {
                alignment     = ConvertAlignment(AdornedComboBox.HorizontalContentAlignment);
                flowDirection = AdornedComboBox.FlowDirection;
                fontSize      = AdornedComboBox.FontSize;
                typeFace      = AdornedComboBox.FontFamily.GetTypefaces().FirstOrDefault();
            }
            var text = new System.Windows.Media.FormattedText(PlaceholderText ?? "", CultureInfo.CurrentCulture, flowDirection, typeFace, fontSize, System.Windows.Media.Brushes.LightGray);


            if (!multiline)
            {
                ypos = (RenderSize.Height - text.Height) / 2;
            }

            switch (alignment)
            {
            case TextAlignment.Center:
                xpos = (RenderSize.Width - text.Width) * 0.5;
                break;

            case TextAlignment.Right:
                xpos = (RenderSize.Width - text.Width) - 6;
                break;
            }

            drawingContext.DrawText(text, new System.Windows.Point(xpos, ypos));
        }
Beispiel #52
0
        public void DrawText(Font font, SolidBrush b, float x, float y, string text)
        {
            var fontHandler = font.Handler as FontHandler;

            if (fontHandler != null)
            {
                var brush         = b.ToWpf();
                var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.PixelSize, brush);
                if (fontHandler.WpfTextDecorations != null)
                {
                    formattedText.SetTextDecorations(fontHandler.WpfTextDecorations, 0, text.Length);
                }
                Control.DrawText(formattedText, new sw.Point(x, y));
            }
        }
Beispiel #53
0
        public static System.Windows.Media.FormattedText ToWpf(this FormattedText ft)
        {
            var typeface = new Typeface(new FontFamily("Arial"), new FontStyle(), ft.FontWeight.ToWpf(), new FontStretch());

            var formattedText = new System.Windows.Media.FormattedText(ft.Text,
                                                                       CultureInfo.CurrentCulture,
                                                                       FlowDirection.LeftToRight,
                                                                       typeface, ft.FontSize,
                                                                       ft.Brush.ToWpf(), new NumberSubstitution(), 3D)
            {
                MaxTextWidth  = double.IsInfinity(ft.Constraint.Width) ? 0 : ft.Constraint.Width,
                MaxTextHeight = ft.Constraint.Height,
            };

            return(formattedText);
        }
Beispiel #54
0
        private void drawGraph(IDrawable start, double startX, double startY)
        {
            start.draw(startX, startY,
                       start.width(
                           (codeString, fontHeight) =>
            {
                System.Windows.Media.FormattedText formattedText = new System.Windows.Media.FormattedText(codeString,
                                                                                                          System.Globalization.CultureInfo.GetCultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight,
                                                                                                          new System.Windows.Media.Typeface(fontFamily), fontHeight, System.Windows.Media.Brushes.Transparent);

                return(formattedText.Width);
            }),

                       (x1, y1, x2, y2) =>
            {
                System.Windows.Shapes.Line line = new System.Windows.Shapes.Line()
                {
                    Visibility      = System.Windows.Visibility.Visible,
                    StrokeThickness = lineThickness,
                    Stroke          = System.Windows.Media.Brushes.Black,
                    X1 = x1,
                    Y1 = y1,
                    X2 = x2,
                    Y2 = y2
                };

                updateCounters(x1, y1, x2, y2);

                this.drawingCanvas.Children.Add(line);
            },

                       (text, fontHeight, x, y) =>
            {
                System.Windows.Controls.TextBlock textBlock = new System.Windows.Controls.TextBlock()
                {
                    FontSize        = fontHeight,
                    Text            = text,
                    RenderTransform = new System.Windows.Media.TranslateTransform(x, y),

                    FontFamily = new System.Windows.Media.FontFamily(fontFamily)
                };
                primaryPath.Content += textBlock.Text + " || ";
                this.drawingCanvas.Children.Add(textBlock);
            });

            resizeCanvas();
        }
Beispiel #55
0
        /// <summary>
        /// 绘制文字;
        /// </summary>
        /// <param name="text"></param>
        /// <param name="emSize"></param>
        /// <param name="foreground"></param>
        /// <param name="origin"></param>
        public void DrawText(string text, double emSize, Brush foreground, Vector2D origin, double angle = 0)
        {
            ValidateDrawingContext();

            var originScreenPoint       = _canvasProxy.ToScreen(origin);
            var nativeOriginScreenPoint = Vector2DAdapter.ConvertToSystemPoint(originScreenPoint);

            var ft = new SystemMedia.FormattedText(
                text,
                System.Globalization.CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight, TypeFace,
                emSize,
                BrushAdapter.ConvertToSystemBrush(foreground)
                );

            DrawFormattedTextCore(ft, origin, angle);
        }
Beispiel #56
0
        public SizeF MeasureString(Font font, string text)
        {
            var result = SizeF.Empty;

            var fontHandler = font.Handler as FontHandler;

            if (fontHandler != null)
            {
                var brush = new swm.SolidColorBrush(swm.Colors.White);
#pragma warning disable CS0618 // 'FormattedText.FormattedText(string, CultureInfo, FlowDirection, Typeface, double, Brush)' is obsolete: 'Use the PixelsPerDip override'
                var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.WpfSize, brush);
#pragma warning restore CS0618 // Type or member is obsolete
                result = new SizeF((float)formattedText.WidthIncludingTrailingWhitespace, (float)formattedText.Height);
            }

            return(result);
        }
Beispiel #57
0
        // https://social.msdn.microsoft.com/Forums/sharepoint/en-US/6cd49173-b06d-4749-85aa-f6ab46c7d4af/wpf-rich-text-box-width-size-adjust-to-text?forum=wpf
        public static swm.FormattedText GetFormattedText(this swd.FlowDocument doc)
        {
            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }


            var runsAndParagraphs = GetRunsAndParagraphs(doc).ToList();
            var output            = new swm.FormattedText(
                GetText(runsAndParagraphs),
                CultureInfo.CurrentCulture,
                doc.FlowDirection,
                new swm.Typeface(doc.FontFamily, doc.FontStyle, doc.FontWeight, doc.FontStretch),
                doc.FontSize,
                doc.Foreground,
                null,
                swm.TextOptions.GetTextFormattingMode(doc));

            int offset = 0;

            foreach (var el in runsAndParagraphs)
            {
                var run = el as swd.Run;

                if (run != null)
                {
                    int count = run.Text.Length;

                    output.SetFontFamily(run.FontFamily, offset, count);
                    output.SetFontStyle(run.FontStyle, offset, count);
                    output.SetFontWeight(run.FontWeight, offset, count);
                    output.SetFontSize(run.FontSize, offset, count);
                    output.SetForegroundBrush(run.Foreground, offset, count);
                    output.SetFontStretch(run.FontStretch, offset, count);
                    output.SetTextDecorations(run.TextDecorations, offset, count);

                    offset += count;
                    continue;
                }
                offset += Environment.NewLine.Length;
            }

            return(output);
        }
Beispiel #58
0
        public void DrawText(Font font, Brush b, float x, float y, string text)
        {
            SetOffset(false);
            var fontHandler = font.Handler as FontHandler;

            if (fontHandler != null)
            {
                var brush = b.ToWpf();
#pragma warning disable CS0618 // 'FormattedText.FormattedText(string, CultureInfo, FlowDirection, Typeface, double, Brush)' is obsolete: 'Use the PixelsPerDip override'
                var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.WpfSize, brush);
#pragma warning restore CS0618 // Type or member is obsolete
                if (fontHandler.WpfTextDecorationsFrozen != null)
                {
                    formattedText.SetTextDecorations(fontHandler.WpfTextDecorationsFrozen, 0, text.Length);
                }
                Control.DrawText(formattedText, new sw.Point(x, y));
            }
        }
Beispiel #59
0
        private SWM.FormattedText GetFormattedText(string textToFormat)
        {
            var ft = new SWM.FormattedText(
                textToFormat,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new SWM.Typeface("Arial"),
                13,
                SWM.Brushes.White,
                null,
                SWM.TextFormattingMode.Display,
                1d);

            ft.SetFontWeight(FontWeights.Regular);
            ft.TextAlignment = TextAlignment.Left;

            return(ft);
        }
Beispiel #60
0
        public static void DrawString(ref Canvas obj, Point p, double size, string font, bool b, bool i, bool u, string text, MEDIA.Color color, double angle)
        {
            TextBlock tb = new TextBlock
            {
                Text       = text,
                FontSize   = size,
                FontFamily = new MEDIA.FontFamily(font),
                Foreground = new MEDIA.SolidColorBrush(color)
            };

            if (b)
            {
                tb.FontWeight = System.Windows.FontWeights.Bold;
            }
            if (i)
            {
                tb.FontStyle = System.Windows.FontStyles.Italic;
            }
            if (u)
            {
                tb.TextDecorations = System.Windows.TextDecorations.Underline;
            }
            var formattedText = new MEDIA.FormattedText(
                tb.Text,
                System.Globalization.CultureInfo.CurrentCulture,
                System.Windows.FlowDirection.LeftToRight,
                new MEDIA.Typeface(tb.FontFamily, tb.FontStyle, tb.FontWeight, tb.FontStretch),
                tb.FontSize,
                tb.Foreground,
                new MEDIA.NumberSubstitution(),
                MEDIA.TextFormattingMode.Display);

            tb.Margin = new System.Windows.Thickness(p.X - formattedText.Width / 2, p.Y - formattedText.Height / 2, 0, 0);
            if (angle != 0)
            {
                tb.RenderTransform = new MEDIA.RotateTransform(angle, formattedText.Width / 2, formattedText.Height / 2);
            }
            obj.Children.Add(tb);
        }