コード例 #1
0
        public InstructionTextDisplayElement()
        {
            this.storyService = App.Current.GetService <StoryService>();
            this.builder      = new InstructionTextBuilder();

            TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);
        }
コード例 #2
0
        public static FrameworkElement MakeSingleLineItem(BadgeCaps device, string message, bool halfSize = false, bool fullWidth = true)
        {
            var   size    = halfSize ? 7 : 12;
            var   font    = new FontFamily(halfSize ? "Lucida Console" : "Arial");
            Brush color   = Brushes.White;
            var   element = new TextBlock()
            {
                Text                = message,
                Background          = Brushes.Transparent,
                FontSize            = size,
                Margin              = halfSize ? new Thickness(0, 0, 0, -1) : new Thickness(0, -2, 0, 0),
                FontFamily          = font,
                TextWrapping        = TextWrapping.NoWrap,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                TextAlignment       = System.Windows.TextAlignment.Center,
                Foreground          = color,
                MinWidth            = !fullWidth || halfSize ? 0 : device.Width,
                UseLayoutRounding   = true,
                SnapsToDevicePixels = true
            };

            TextOptions.SetTextFormattingMode(element, TextFormattingMode.Display);
            TextOptions.SetTextRenderingMode(element, TextRenderingMode.Aliased);
            TextOptions.SetTextHintingMode(element, TextHintingMode.Fixed);

            return(element);
        }
コード例 #3
0
ファイル: Game.cs プロジェクト: mikairi/SoshiLand
        public Game()
        {
            TextOptions.SetTextHintingMode(this, TextHintingMode.Animated);

            this.Window  = new GameWindow();
            this.Content = new ContentManager(services);

            // Wait until we're loaded and then do the startup sequence:
            this.Loaded += new RoutedEventHandler(StartGame);
        }
コード例 #4
0
ファイル: WpfHelper.VS.cs プロジェクト: wangjieest/Codist
 public static void SetUITextRenderOptions(DependencyObject element, bool optimize)
 {
     if (element == null)
     {
         return;
     }
     //TextOptions.SetTextFormattingMode(element, optimize ? TextFormattingMode.Ideal : TextFormattingMode.Display);
     TextOptions.SetTextHintingMode(element, optimize ? TextHintingMode.Fixed : TextHintingMode.Auto);
     TextOptions.SetTextRenderingMode(element, optimize ? TextRenderingMode.Grayscale : TextRenderingMode.Auto);
 }
コード例 #5
0
        public Game()
        {
            TextOptions.SetTextHintingMode(this, TextHintingMode.Animated);

            // TODO: What is the correct startup state for Window?
            this.Window = new GameWindow();
            Window.DoClientSizeChange(new Rectangle(0, 0, (int)Width, (int)Height));

            this.Content = new ContentManager(services);

            // Wait until we're loaded and then do the startup sequence:
            this.Loaded += new RoutedEventHandler(StartGame);
        }
コード例 #6
0
ファイル: TimeStampMargin.cs プロジェクト: zyonet/VS-PPT
        /// <summary>
        /// Creates a <see cref="TimeStampMargin"/> for a given <see cref="IWpfTextView"/>.
        /// </summary>
        public TimeStampMargin(IWpfTextView textView, MarginFactory factory)
        {
            _textView = textView;
            _factory  = factory;

            this.IsHitTestVisible = false;
            this.ClipToBounds     = true;
            this.Children.Add(_translatedCanvas);

            _lineNumberClassification = _factory.ClassificationTypeRegistryService.GetClassificationType(LineNumberClassificationTypeKey);
            _formatMap = _factory.ClassificationFormatMappingService.GetClassificationFormatMap(_textView);

            // Enable the fixed text hinting mode to ensure that WPF never considers
            // the text as being animated. If it does, it will use a lower resolution to render
            // the text during animation (scrolling for instance) which makes the text look fuzzy
            // and then sharp once the animation stops
            TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);

            _textView.TextBuffer.Changed += OnTextBufferChanged;

            ITextSnapshot snapshot = _textView.TextBuffer.CurrentSnapshot;

            for (int i = snapshot.LineCount - 2; (i >= 0); --i)     //Do not add the time stamp for the last line of the buffer (the one without a line break)
            {
                _lineTimeStamps.Add(DateTime.Now);
            }

            base.IsVisibleChanged += delegate(object sender, DependencyPropertyChangedEventArgs e)
            {
                if ((bool)e.NewValue)
                {
                    // Raised whenever the text in a text view changes.
                    _textView.LayoutChanged += OnLayoutChanged;

                    // Raised whenever the options for a text view changes.
                    _textView.Options.OptionChanged += OnOptionChanged;

                    // Raised whenever the classification format changes.
                    _formatMap.ClassificationFormatMappingChanged += OnClassificationFormatChanged;

                    //Fonts might have changed while we were hidden.
                    this.SetFontFromClassification();
                }
                else
                {
                    _textView.LayoutChanged         -= OnLayoutChanged;
                    _textView.Options.OptionChanged -= OnOptionChanged;
                    _formatMap.ClassificationFormatMappingChanged -= OnClassificationFormatChanged;
                }
            };
        }
コード例 #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AppWindow"/> class.
 /// </summary>
 public AppWindow()
 {
     MinimizeCommand    = RelayCommand.Create((p) => WindowState = WindowState.Minimized);
     ChangeStateCommand = RelayCommand.Create(RunChangeStateCommand);
     CloseCommand       = RelayCommand.Create((p) => Close());
     /* see comments in this method */
     SetMaxHeight();
     /* see comments in this method */
     SystemParameters.StaticPropertyChanged += SystemParametersStaticPropertyChanged;
     Loaded           += (s, e) => OnLoaded(s, e);
     UseLayoutRounding = true;
     //RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);
     // Default for the following is: Auto, Ideal, Auto
     TextOptions.SetTextRenderingMode(this, TextRenderingMode.ClearType);
     TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);
     TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);
 }
コード例 #8
0
        private static FrameworkElement CreateElement(string text, IWpfTextView textView, TextFormattingRunProperties format)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a font size 1/4 smaller than the font size of the rest of the editor
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = format.FontRenderingEmSize - (0.25 * format.FontRenderingEmSize),
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 0, bottom: 0),
                Text              = text + ":",
                VerticalAlignment = VerticalAlignment.Center,
            };

            // Encapsulates the textblock within a border. Sets the height of the border to be 3/4 of the original
            // height. Gets foreground/background colors from the options menu. The margin is the distance from the
            // adornment to the text and pushing the adornment upwards to create a separation when on a specific line
            var border = new Border
            {
                Background          = format.BackgroundBrush,
                Child               = block,
                CornerRadius        = new CornerRadius(2),
                Height              = textView.LineHeight - (0.25 * textView.LineHeight),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin              = new Thickness(left: 0, top: -0.20 * textView.LineHeight, right: 5, bottom: 0),
                Padding             = new Thickness(1),

                // Need to set SnapsToDevicePixels and UseLayoutRounding to avoid unnecessary reformatting
                SnapsToDevicePixels = textView.VisualElement.SnapsToDevicePixels,
                UseLayoutRounding   = textView.VisualElement.UseLayoutRounding,
                VerticalAlignment   = VerticalAlignment.Center
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }
コード例 #9
0
        private Grid GetRoot()
        {
            var root = new Grid()
            {
                //Background = Brushes.LightCoral,
                Margin = this.PageMargins,
                Height = this.PageSize.Height - this.PageMargins.Top - this.PageMargins.Bottom, // TODO: cache available space
                Width  = this.PageSize.Width - this.PageMargins.Left - this.PageMargins.Right,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Stretch
            };

            TextOptions.SetTextFormattingMode(root, TextFormattingMode.Ideal);
            TextOptions.SetTextHintingMode(root, TextHintingMode.Fixed);
            TextOptions.SetTextRenderingMode(root, TextRenderingMode.Auto);

            return(root);
        }
コード例 #10
0
        public TimeStampMargin(IWpfTextView textView, TimeStampMarginProvider timeStampMarginProvider)
        {
            _textView = textView;

            _formatMap = timeStampMarginProvider.ClassificationFormatMappingService
                         .GetClassificationFormatMap(_textView);

            _timestampClassification = timeStampMarginProvider.ClassificationTypeRegistryService
                                       .GetClassificationType(ClassificationTypeDefinitions.TimeStamp);

            ClipToBounds     = true;
            IsHitTestVisible = false;
            Children.Add(_translatedCanvas);
            TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);

            IsVisibleChanged             += OnVisibleChanged;
            _textView.TextBuffer.Changed += TextBufferOnChanged;
            Settings.SettingsUpdated     += OnSettingsOnSettingsUpdated;
            UpdateFormatMap();
        }
コード例 #11
0
ファイル: AppBase.cs プロジェクト: mightycow/ubermmemuxer
        protected void CreateWindow()
        {
            var window = new Window();

            MainWindow                = window;
            window.Closing           += (obj, args) => OnQuit();
            window.WindowStyle        = WindowStyle.SingleBorderWindow;
            window.AllowsTransparency = false;
            window.Background         = new SolidColorBrush(System.Windows.SystemColors.ControlColor);
            window.ShowInTaskbar      = true;
            window.Title              = "UMM";
            window.Content            = RootPanel;
            window.Width              = 1024;
            window.Height             = 768;
            window.MinWidth           = 1024;
            window.MinHeight          = 768;
            TextOptions.SetTextRenderingMode(window, TextRenderingMode.ClearType);
            TextOptions.SetTextHintingMode(window, TextHintingMode.Fixed);
            TextOptions.SetTextFormattingMode(window, TextFormattingMode.Display);
        }
コード例 #12
0
 void SetLayoutOptions(FrameworkElement adornment)
 {
     TextOptions.SetTextFormattingMode(adornment, m_textFormattingMode);
     TextOptions.SetTextHintingMode(adornment, m_textHintingMode);
     TextOptions.SetTextRenderingMode(adornment, m_textRenderingMode);
 }
コード例 #13
0
ファイル: TextEditProxy.cs プロジェクト: radtek/Shopdrawing
        public virtual void Instantiate()
        {
            if (!this.TextSource.ViewModel.ProjectContext.IsCapabilitySet(PlatformCapability.SupportsTabInTextControl))
            {
                this.EditingElement.KeyDown += new KeyEventHandler(this.DisableTabHandler);
            }
            else
            {
                this.EditingElement.AcceptsTab = true;
            }
            this.EditingElement.SetValue(this.ProxyPlatform.Metadata.DefaultTypeResolver, DesignTimeProperties.IsTextEditProxyProperty, (object)true);
            this.EditingElement.IsSpellCheckEnabled  = true;
            this.EditingElement.IsUndoEnabled        = true;
            this.EditingElement.IsEnabled            = true;
            this.EditingElement.AcceptsReturn        = true;
            this.EditingElement.IsInputMethodEnabled = true;
            if (this.TextSource.ProjectContext.IsCapabilitySet(PlatformCapability.IsWpf) || !PlatformTypes.ContentControl.IsAssignableFrom((ITypeId)this.TextSource.Type))
            {
                this.CopyProperty(ControlElement.BackgroundProperty);
                this.CopyProperty(ControlElement.ForegroundProperty);
            }
            if (!this.TextSource.ProjectContext.IsCapabilitySet(PlatformCapability.IsWpf) && PlatformTypes.TextBlock.IsAssignableFrom((ITypeId)this.TextSource.Type))
            {
                TextBoxBase textBoxBase = this.EditingElement.PlatformSpecificObject as TextBoxBase;
                if (textBoxBase != null)
                {
                    textBoxBase.Background = (Brush)Brushes.Transparent;
                }
            }
            IProperty property1 = this.TextSource.ProjectContext.ResolveProperty(TextOptionsProperties.TextFormattingModeProperty);

            if (property1 != null)
            {
                object      computedValueAsWpf = this.TextSource.GetComputedValueAsWpf((IPropertyId)property1);
                TextBoxBase textBoxBase        = this.EditingElement.PlatformSpecificObject as TextBoxBase;
                if (textBoxBase != null && computedValueAsWpf is TextFormattingMode)
                {
                    TextOptions.SetTextFormattingMode((DependencyObject)textBoxBase, (TextFormattingMode)computedValueAsWpf);
                }
            }
            IProperty property2 = this.TextSource.ProjectContext.ResolveProperty(TextOptionsProperties.TextHintingModeProperty);

            if (property2 != null)
            {
                object      computedValueAsWpf = this.TextSource.GetComputedValueAsWpf((IPropertyId)property2);
                TextBoxBase textBoxBase        = this.EditingElement.PlatformSpecificObject as TextBoxBase;
                if (textBoxBase != null && computedValueAsWpf is TextHintingMode)
                {
                    TextOptions.SetTextHintingMode((DependencyObject)textBoxBase, (TextHintingMode)computedValueAsWpf);
                }
            }
            this.CopyProperty(ControlElement.FontFamilyProperty);
            this.CopyProperty(ControlElement.FontSizeProperty);
            this.CopyProperty(ControlElement.BorderBrushProperty);
            this.CopyProperty(ControlElement.BorderThicknessProperty);
            this.CopyProperty(ControlElement.FontStretchProperty);
            this.CopyProperty(ControlElement.FontStyleProperty);
            this.CopyProperty(ControlElement.FontWeightProperty);
            this.CopyProperty(Base2DElement.OpacityProperty);
            this.CopyProperty(ControlElement.PaddingProperty);
            if (this.TextSource.ProjectContext.IsCapabilitySet(PlatformCapability.IsWpf))
            {
                this.CopyProperty(DesignTimeProperties.InstanceBuilderContextProperty);
            }
            else
            {
                this.EditingElement.InstanceBuilderContext = (object)new WeakReference((object)this.textSource.ViewModel.DefaultView.InstanceBuilderContext);
            }
            this.DisableUndo();
        }
コード例 #14
0
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work
            // well with VS at any zoom level or font size.

            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = 0.75 * format.FontRenderingEmSize,
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 1, bottom: 0),
                VerticalAlignment = VerticalAlignment.Center,
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu.

            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background   = format.BackgroundBrush,
                Child        = block,
                CornerRadius = new CornerRadius(2),

                // Place 3 pixels above/below the border object.  This works well as the highlighting lines are 2px
                // each, giving us 1 px of space on both side of the inline tag and them.  This gives the inline tag
                // an appropriate floating-halfway feeling on the line.
                Margin = new Thickness(left, top: 3, right, bottom: 3),
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }
        public DocumentEditorContextView(DocumentEditorContext editor)
        {
            _viewFactory          = new ViewFactory();
            _blockSearchHitTester = new BlockSearchHitTester(this);

            editor.Tag = this;
            Focusable  = true;

            TextElement.SetFontSize(this, 16);
            TextElement.SetFontFamily(this, new FontFamily("Times New Roman"));
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);
            TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);
            TextOptions.SetTextRenderingMode(this, TextRenderingMode.ClearType);

            Cursor = Cursors.IBeam;

            _editor = editor;

            _cursorView = new DocumentCursorView(_editor.Selection);

            // clear out the existing content
            _blockCollectionView = new VerticalBlockCollectionView(this, _editor.Document.Root)
            {
                Background = Brushes.White,
            };

            _scrollView = new ScrollViewer
            {
                Background = new SolidColorBrush(Color.FromRgb(244, 244, 244)),
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
            };
            Children.Add(_scrollView);

            SetTop(_scrollView, 0);
            SetLeft(_scrollView, 0);
            SetZIndex(_scrollView, 0);

            // use a grid simply because it's convenient.  What we really need is a canvas (for absolute
            // positioning) that overlays the content of the scroll viewer.
            var layoutGrid = new Grid
            {
                Margin = new Thickness(50),
            };

            _scrollView.Content = new Border()
            {
                BorderBrush     = new SolidColorBrush(Color.FromRgb(158, 158, 158)),
                BorderThickness = new Thickness(1),
                Margin          = new Thickness(20),
                Child           = new Border()
                {
                    Background = new SolidColorBrush(Colors.White),
                    Child      = layoutGrid,
                },
                Width  = 800,
                Height = 1000,
                HorizontalAlignment = HorizontalAlignment.Center,
            };

            // simply add the content in
            layoutGrid.Children.Add(new StackPanel
            {
                Background = Brushes.Transparent,
                Children   =
                {
                    _blockCollectionView
                }
            });

            var layoutAbsolute = new Canvas();

            layoutGrid.Children.Add(layoutAbsolute);

            UIElementCollection parentCollection = layoutAbsolute.Children;

            parentCollection.Add(_cursorView);

            var keyboardShortcutCollection = ConfigureCommands();

            _keyCommands = keyboardShortcutCollection;

            InsertText("This is an example of a document within the editor. జో It has many features that extend onto " +
                       "multiple lines enough that we can start to create paragraphs.  Don't also forget" +
                       "about X & Y and those other things that extend the line length for the X-Files.  " +
                       "Isn't that great? జో");

            ((IContextualCommand) new BreakTextBlockCommand()).Activate(_editor, _editor.UndoStack);

            InsertText("Another paragraph with addition text sits here, right where you need it to be.");

            //var listItem = new ListItemBlock();
            //document.Root.Append(listItem);
            //var cursor = ((Core.ObjectModel.Blocks.Text.TextBlock)listItem.FirstBlock).GetTextCursor();
            //cursor.MoveToBeginning();
            //cursor.InsertText("A list item");

            _editor.UndoStack.Clear();

            layoutGrid.PreviewMouseDown += HandlePreviewMouseDown;
            layoutGrid.PreviewMouseUp   += HandlePreviewMouseUp;
            layoutGrid.PreviewMouseMove += HandlePreviewMouseMove;

            BlockSearchHitTester.SetShouldStopHitTesting(_cursorView, true);
            BlockSearchHitTester.SetShouldStopHitTesting(layoutAbsolute, true);

            Loaded   += OnLoaded;
            Unloaded += OnUnloaded;
        }
コード例 #16
0
ファイル: InlineHintsTag.cs プロジェクト: josh-127/roslyn
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work
            // well with VS at any zoom level or font size.
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = 0.75 * format.FontRenderingEmSize,
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,
                // Adds a little bit of padding to the left of the text relative to the border to make the text seem
                // more balanced in the border
                Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0)
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu.
            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background        = format.BackgroundBrush,
                Child             = block,
                CornerRadius      = new CornerRadius(2),
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin            = new Thickness(left, top: 0, right, bottom: 0),
            };

            // gets pixel distance of baseline to top of the font height
            var dockPanelHeight = format.Typeface.FontFamily.Baseline * format.FontRenderingEmSize;
            var dockPanel       = new DockPanel
            {
                Height        = dockPanelHeight,
                LastChildFill = false,
                // VerticalAlignment is set to Top because it will rest to the top relative to the stackpanel
                VerticalAlignment = VerticalAlignment.Top
            };

            dockPanel.Children.Add(border);
            DockPanel.SetDock(border, Dock.Bottom);

            var stackPanel = new StackPanel
            {
                // Height set to align the baseline of the text within the TextBlock with the baseline of text in the editor
                Height      = dockPanelHeight + (block.DesiredSize.Height - (block.FontFamily.Baseline * block.FontSize)),
                Orientation = Orientation.Vertical
            };

            stackPanel.Children.Add(dockPanel);
            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(stackPanel, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(stackPanel, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(stackPanel, TextOptions.GetTextRenderingMode(textView.VisualElement));

            return(stackPanel);
        }
コード例 #17
0
        private void SetBitmap()
        {
            int width  = (int)textbox.ActualWidth;
            int height = (int)textbox.ActualHeight;

            if (width <= 0 || height <= 0)
            {
                return;
            }
            WriteableBitmap buffer;

            var bgColor = Color.FromRgb(0xF9, 0xF9, 0xF9);

            textImage1.Width  = width;
            textImage1.Height = height;
            buffer            = BitmapFactory.New(width, height);
            buffer.Clear(bgColor);
            //buffer.DrawString(0, 0, Colors.Black, new Typeface("Arial"), 12, "ABC 123 Gfijdr");
            buffer.DrawString(0, 0, Colors.Black, new PortableFontDesc(isbold: true), "Transparency");
            buffer.DrawLine(0, 10, 50, 10, Colors.Black);
            buffer.DrawLine(50, 0, 50, 40, Colors.Black);
            textImage1.Source = buffer;

            textImage2.Width  = width;
            textImage2.Height = height;
            buffer            = BitmapFactory.New(width, height);
            buffer.Clear(bgColor);
            buffer.DrawString(0, 0, Colors.Black, bgColor, new PortableFontDesc(cleartype: true), "ABC 123 Gfijdr");
            textImage2.Source = buffer;

            textImage3.Width  = width;
            textImage3.Height = height;


            var text = new FormattedText("ABC l 123 Gfijdr",
                                         CultureInfo.InvariantCulture,
                                         FlowDirection.LeftToRight,
                                         new Typeface("Arial"),
                                         12,
                                         new SolidColorBrush(Colors.Black));


            var drawingVisual = new DrawingVisual();

            RenderOptions.SetBitmapScalingMode(drawingVisual, BitmapScalingMode.NearestNeighbor);
            RenderOptions.SetClearTypeHint(drawingVisual, ClearTypeHint.Enabled);
            RenderOptions.SetEdgeMode(drawingVisual, EdgeMode.Aliased);
            TextOptions.SetTextRenderingMode(drawingVisual, TextRenderingMode.ClearType);
            TextOptions.SetTextFormattingMode(drawingVisual, TextFormattingMode.Display);
            TextOptions.SetTextHintingMode(drawingVisual, TextHintingMode.Fixed);

            using (var drawingContext = drawingVisual.RenderOpen())
            {
                //var brush = new VisualBrush(new TextBlock {Text = "ABC 123 Gfijdr"});
                //drawingContext.DrawRectangle(brush, null, new Rect(0, 0, width, height));

                //Double halfPenWidth = 0.5;

                //var face = new Typeface("Arial");
                //GlyphTypeface gt;
                //face.TryGetGlyphTypeface(out gt);
                //var indexes = new ushort[] {gt.CharacterToGlyphMap['A']};
                //var widths = new double[] {gt.AdvanceWidths['A']*12};

                //var glyphRun = new GlyphRun(gt, 0, false, 12, indexes, new Point(0, 14), widths, null, null, null, null, null, null);
                //var rect = glyphRun.ComputeAlignmentBox();

                //Double halfPenWidth = 0.5;
                ////var rect = new Rect(0, 0, width, height);
                //GuidelineSet guidelines = new GuidelineSet();
                //guidelines.GuidelinesX.Add(rect.Left + halfPenWidth);
                //guidelines.GuidelinesX.Add(rect.Right + halfPenWidth);
                //guidelines.GuidelinesY.Add(rect.Top + halfPenWidth);
                //guidelines.GuidelinesY.Add(rect.Bottom + halfPenWidth);

                drawingContext.DrawRectangle(new SolidColorBrush(bgColor), null, new Rect(0, 0, width, height));

                drawingContext.DrawText(text, new Point(0, 0));
                drawingContext.DrawLine(new Pen(Brushes.Black, 1), new Point(0.5, 10.5), new Point(50.5, 10.5));
                drawingContext.DrawLine(new Pen(Brushes.Black, 1), new Point(35.5, 0.5), new Point(35.5, 40.5));

                //drawingContext.PushGuidelineSet(guidelines);
                //drawingContext.DrawGlyphRun(Brushes.Black, glyphRun);
                //drawingContext.Pop();
            }
            //drawingVisual.Transform = new ScaleTransform(0.9, 0.9);
            //drawingVisual.Transform = new ScaleTransform(1, 1);
            //drawingVisual.Transform = new TranslateTransform(0, -0.25);

            var tb = new TextBlock {
                Text = "ABC l 123 Gfijdr"
            };

            tb.Measure(new Size(width, height));
            tb.Arrange(new Rect(new Point(0, 0), new Size(width, height)));

            var bmp = new RenderTargetBitmap(width, height, DpiDetector.DpiXKoef * 96, DpiDetector.DpiYKoef * 96, PixelFormats.Pbgra32);

            RenderOptions.SetBitmapScalingMode(bmp, BitmapScalingMode.NearestNeighbor);
            RenderOptions.SetClearTypeHint(bmp, ClearTypeHint.Enabled);
            RenderOptions.SetEdgeMode(bmp, EdgeMode.Aliased);
            TextOptions.SetTextRenderingMode(bmp, TextRenderingMode.ClearType);
            TextOptions.SetTextFormattingMode(bmp, TextFormattingMode.Display);
            TextOptions.SetTextHintingMode(bmp, TextHintingMode.Fixed);

            //RenderOptions.SetCachingHint(bmp, CachingHint.Cache);
            //RenderOptions.SetBitmapScalingMode(bmp, BitmapScalingMode.LowQuality);
            bmp.Render(drawingVisual);
            //bmp.Render(tb);
            //bmp.Freeze();


            BitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));

            var ms = new MemoryStream();

            encoder.Save(ms);

            BitmapImage bi = new BitmapImage();

            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();

            encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            using (var fs = System.IO.File.OpenWrite("file1.png"))
            {
                encoder.Save(fs);
            }

            textImage3.Stretch = Stretch.None;
            textImage3.Source  = bmp;
        }
コード例 #18
0
ファイル: InlineHintsTag.cs プロジェクト: rukykf/roslyn
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a font size 1/4 smaller than the font size of the rest of the editor
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = format.FontRenderingEmSize - (0.25 * format.FontRenderingEmSize),
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 1, bottom: 0),
                VerticalAlignment = VerticalAlignment.Center,
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            // Encapsulates the textblock within a border. Sets the height of the border to be 3/4 of the original
            // height. Gets foreground/background colors from the options menu. The margin is the distance from the
            // adornment to the text and pushing the adornment upwards to create a separation when on a specific line

            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background          = format.BackgroundBrush,
                Child               = block,
                CornerRadius        = new CornerRadius(2),
                Height              = textView.LineHeight - (0.25 * textView.LineHeight),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin              = new Thickness(left, top: -0.20 * textView.LineHeight, right, bottom: 0),
                Padding             = new Thickness(1),

                // Need to set SnapsToDevicePixels and UseLayoutRounding to avoid unnecessary reformatting
                SnapsToDevicePixels = textView.VisualElement.SnapsToDevicePixels,
                UseLayoutRounding   = textView.VisualElement.UseLayoutRounding,
                VerticalAlignment   = VerticalAlignment.Center
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }
コード例 #19
0
        private double RenderText(double initialAngle, bool measureOnly, int startChild = 0)
        {
            double currentAngle = initialAngle;

            totalWidth = 0;
            for (int i = 0; i < Text.Length; i++)
            {
                TextBlock textSegment = null;

                if (startChild + i < LayoutRoot.Children.Count)
                {
                    textSegment = LayoutRoot.Children[startChild + i] as TextBlock;
                }

                if (textSegment == null)
                {
                    textSegment = new TextBlock();

                    if (this.FontFamily != null)
                    {
                        textSegment.FontFamily = this.FontFamily;
                    }

                    DropShadowEffect shadow = new DropShadowEffect();
                    shadow.BlurRadius      = 6.0;
                    shadow.Color           = Colors.White;
                    shadow.ShadowDepth     = 0;
                    textSegment.Effect     = shadow;
                    textSegment.FontWeight = FontWeights.Normal;
                    textSegment.MinWidth   = 0;
                    TextOptions.SetTextFormattingMode(textSegment, TextFormattingMode.Ideal);
                    TextOptions.SetTextRenderingMode(textSegment, TextRenderingMode.ClearType);
                    TextOptions.SetTextHintingMode(textSegment, TextHintingMode.Auto);

                    LayoutRoot.Children.Add(textSegment);

                    TransformGroup renderGroup = new TransformGroup();

                    RotateTransform    rotateCenter = new RotateTransform(0);
                    TranslateTransform translate    = new TranslateTransform(0, 0);
                    RotateTransform    rotate       = new RotateTransform(0);

                    renderGroup.Children.Add(rotateCenter);
                    renderGroup.Children.Add(translate);
                    renderGroup.Children.Add(rotate);

                    textSegment.RenderTransform = renderGroup;
                }
                string character = Text[i].ToString();

                bool dirty = false;
                if (textSegment.Text != character)
                {
                    textSegment.Text = character;
                    dirty            = true;
                }

                textSegment.Foreground = this.Foreground;
                if (textSegment.FontSize != this.FontSize)
                {
                    textSegment.FontSize = this.FontSize;
                    dirty = true;
                }

                if (dirty || !textSegment.IsMeasureValid)
                {
                    textSegment.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                }
                double width  = textSegment.DesiredSize.Width;
                double height = textSegment.DesiredSize.Height;
                totalWidth    += width;
                this.Thickness = height;

                double effectiveRadius = Radius;

                if (IsInverted)
                {
                    effectiveRadius = -(Radius + height);
                }
                double alignedRadius = Radius;

                if (VerticalAlignment == System.Windows.VerticalAlignment.Top)
                {
                    alignedRadius -= height;

                    if (IsInverted)
                    {
                        effectiveRadius += height;
                    }
                    else
                    {
                        effectiveRadius -= height;
                    }
                }

                double deltaAngle = Math.Atan2(width, Math.Abs(alignedRadius)) * 180.0 / Math.PI;

                if (measureOnly == false)
                {
                    TransformGroup renderGroup = textSegment.RenderTransform as TransformGroup;

                    RotateTransform rotateCenter = renderGroup.Children[0] as RotateTransform;
                    double          deltaAngle2  = deltaAngle / 2.0;
                    if (rotateCenter.Angle != deltaAngle2)
                    {
                        rotateCenter.Angle = deltaAngle2;
                    }
                    rotateCenter.CenterX = width / 2;
                    rotateCenter.CenterY = height;

                    TranslateTransform translate = renderGroup.Children[1] as TranslateTransform;
                    translate.Y = effectiveRadius;

                    RotateTransform rotate = renderGroup.Children[2] as RotateTransform;
                    rotate.Angle = currentAngle;
                }
                if (IsInverted)
                {
                    currentAngle += deltaAngle;
                }
                else
                {
                    currentAngle -= deltaAngle;
                }
            }

            return(Math.Abs(currentAngle - initialAngle));
        }