Примените штрих к textblock в WPF

Вот еще один пример, когда дерево реализовано в массиве:

#include <stdio.h>
#include <math.h>


#define PARENT(i) ((i-1) / 2)
#define NUM_NODES 15
#define LINE_WIDTH 70

int main() {
    int tree[NUM_NODES]={0,1,2,3,4,5,6,7,8,9,1,2,3,4,5};
    int print_pos[NUM_NODES];
    int i, j, k, pos, x=1, level=0;

    print_pos[0] = 0;
    for(i=0,j=1; i<NUM_NODES; i++,j++) {
        pos = print_pos[PARENT(i)] + (i%2?-1:1)*(LINE_WIDTH/(pow(2,level+1))+1);

        for (k=0; k<pos-x; k++) printf("%c",i==0||i%2?' ':'-');
        printf("%d",tree[i]);

        print_pos[i] = x = pos+1;
        if (j==pow(2,level)) {
            printf("\n");
            level++;
            x = 1;
            j = 0;
        }
    }
    return 0;
}

Выход:

                                   0
                  1-----------------------------------2
          3-----------------4                 5-----------------6
      7---------8       9---------1       2---------3       4---------5
60
задан Kris Erickson 18 September 2008 в 16:37
поделиться

5 ответов

< TextBlock> не имеет никакого декоративного, приписывает себя. Я поместил бы его на < Canvas> с < Rectangle> и примените штрих там.

0
ответ дан kaiz.net 7 November 2019 в 14:00
поделиться

В Смешении Вы могли преобразовать TextBlock в Путь, и затем использовать нормальные Свойства обводки. Но я предполагаю, что Вы хотели что-то, что Вы могли сделать динамичным...

Иначе я думал бы, что это должен будет быть своего рода растровый эффект или специальная кисть.

1
ответ дан Tim Erickson 7 November 2019 в 14:00
поделиться

, "Как к: Создайте Обрисованный в общих чертах текст" на MSDN, имеет всю информацию, в которой Вы нуждаетесь.

2
ответ дан David Archer 7 November 2019 в 14:00
поделиться

необходимо обернуть TextBlock с Границей.. что-то вроде этого:

    <Border BorderBrush="Purple" BorderThickness="2">
        <TextBlock>My fancy TextBlock</TextBlock>
    </Border>

в от шанса Вы спрашиваете, как поместить штрих вокруг фактических букв (а не целый TextBlock) можно хотеть посмотреть на использование BitmapEffect Свечения и установки параметров на Свечении, чтобы быть цветом обводки, который Вы хотите, и т.д. Иначе Вам, вероятно, придется создать что-то пользовательское.

7
ответ дан SmartyP 7 November 2019 в 14:00
поделиться

Найденный Им. Не настолько легкий сделать, по-видимому, существует не создан в Штриховом тексте в WPF (своего рода большая недостающая возможность, если Вы спрашиваете меня). Сначала создайте пользовательский класс:

using System;
using System.Windows.Media;
using System.Globalization;
using System.Windows;
using System.Windows.Markup;

namespace CustomXaml
{

public class OutlinedText : FrameworkElement, IAddChild
{
    #region Private Fields

    private Geometry _textGeometry;

    #endregion

    #region Private Methods

    /// <summary>
    /// Invoked when a dependency property has changed. Generate a new FormattedText object to display.
    /// </summary>
    /// <param name="d">OutlineText object whose property was updated.</param>
    /// <param name="e">Event arguments for the dependency property.</param>
    private static void OnOutlineTextInvalidated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((OutlinedText)d).CreateText();
    }

    #endregion


    #region FrameworkElement Overrides

    /// <summary>
    /// OnRender override draws the geometry of the text and optional highlight.
    /// </summary>
    /// <param name="drawingContext">Drawing context of the OutlineText control.</param>
    protected override void OnRender(DrawingContext drawingContext)
    {
        CreateText();
        // Draw the outline based on the properties that are set.
        drawingContext.DrawGeometry(Fill, new Pen(Stroke, StrokeThickness), _textGeometry);

    }

    /// <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;

    }

    #endregion

    #region DependencyProperties

    /// <summary>
    /// Specifies whether the font should display Bold font weight.
    /// </summary>
    public bool Bold
    {
        get
        {
            return (bool)GetValue(BoldProperty);
        }

        set
        {
            SetValue(BoldProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Bold dependency property.
    /// </summary>
    public static readonly DependencyProperty BoldProperty = DependencyProperty.Register(
        "Bold",
        typeof(bool),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
            false,
            FrameworkPropertyMetadataOptions.AffectsRender,
            new PropertyChangedCallback(OnOutlineTextInvalidated),
            null
            )
        );

    /// <summary>
    /// Specifies the brush to use for the fill of the formatted text.
    /// </summary>
    public Brush Fill
    {
        get
        {
            return (Brush)GetValue(FillProperty);
        }

        set
        {
            SetValue(FillProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Fill dependency property.
    /// </summary>
    public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
        "Fill",
        typeof(Brush),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
            new SolidColorBrush(Colors.LightSteelBlue),
            FrameworkPropertyMetadataOptions.AffectsRender,
            new PropertyChangedCallback(OnOutlineTextInvalidated),
            null
            )
        );

    /// <summary>
    /// The font to use for the displayed formatted text.
    /// </summary>
    public FontFamily Font
    {
        get
        {
            return (FontFamily)GetValue(FontProperty);
        }

        set
        {
            SetValue(FontProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Font dependency property.
    /// </summary>
    public static readonly DependencyProperty FontProperty = DependencyProperty.Register(
        "Font",
        typeof(FontFamily),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
            new FontFamily("Arial"),
            FrameworkPropertyMetadataOptions.AffectsRender,
            new PropertyChangedCallback(OnOutlineTextInvalidated),
            null
            )
        );

    /// <summary>
    /// The current font size.
    /// </summary>
    public double FontSize
    {
        get
        {
            return (double)GetValue(FontSizeProperty);
        }

        set
        {
            SetValue(FontSizeProperty, value);
        }
    }

    /// <summary>
    /// Identifies the FontSize dependency property.
    /// </summary>
    public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register(
        "FontSize",
        typeof(double),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
             (double)48.0,
             FrameworkPropertyMetadataOptions.AffectsRender,
             new PropertyChangedCallback(OnOutlineTextInvalidated),
             null
             )
        );


    /// <summary>
    /// Specifies whether the font should display Italic font style.
    /// </summary>
    public bool Italic
    {
        get
        {
            return (bool)GetValue(ItalicProperty);
        }

        set
        {
            SetValue(ItalicProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Italic dependency property.
    /// </summary>
    public static readonly DependencyProperty ItalicProperty = DependencyProperty.Register(
        "Italic",
        typeof(bool),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
             false,
             FrameworkPropertyMetadataOptions.AffectsRender,
             new PropertyChangedCallback(OnOutlineTextInvalidated),
             null
             )
        );

    /// <summary>
    /// Specifies the brush to use for the stroke and optional hightlight of the formatted text.
    /// </summary>
    public Brush Stroke
    {
        get
        {
            return (Brush)GetValue(StrokeProperty);
        }

        set
        {
            SetValue(StrokeProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Stroke dependency property.
    /// </summary>
    public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
        "Stroke",
        typeof(Brush),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
             new SolidColorBrush(Colors.Teal),
             FrameworkPropertyMetadataOptions.AffectsRender,
             new PropertyChangedCallback(OnOutlineTextInvalidated),
             null
             )
        );

    /// <summary>
    ///     The stroke thickness of the font.
    /// </summary>
    public ushort StrokeThickness
    {
        get
        {
            return (ushort)GetValue(StrokeThicknessProperty);
        }

        set
        {
            SetValue(StrokeThicknessProperty, value);
        }
    }

    /// <summary>
    /// Identifies the StrokeThickness dependency property.
    /// </summary>
    public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
        "StrokeThickness",
        typeof(ushort),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
             (ushort)0,
             FrameworkPropertyMetadataOptions.AffectsRender,
             new PropertyChangedCallback(OnOutlineTextInvalidated),
             null
             )
        );

    /// <summary>
    /// Specifies the text string to display.
    /// </summary>
    public string Text
    {
        get
        {
            return (string)GetValue(TextProperty);
        }

        set
        {
            SetValue(TextProperty, value);
        }
    }

    /// <summary>
    /// Identifies the Text dependency property.
    /// </summary>
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
        "Text",
        typeof(string),
        typeof(OutlinedText),
        new FrameworkPropertyMetadata(
             "",
             FrameworkPropertyMetadataOptions.AffectsRender,
             new PropertyChangedCallback(OnOutlineTextInvalidated),
             null
             )
        );

    public void AddChild(Object value)
    {

    }

    public void AddText(string value)
    {
        Text = value;
    }

    #endregion
}
}

Вы могут сослаться на него в Вашем xaml.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:customControls="clr-namespace:CustomXaml;assembly=CustomXaml">
    <Grid>
        <customControls:OutlinedText x:Name="TextContent" Fill="#ffffffff" FontSize="28"     
Bold="True" Stroke="Black" StrokeThickness="1" Text="Back" Margin="10,0,10,0" 
HorizontalAlignment="Center" VerticalAlignment="Center" Height="Auto" Width="Auto" />
    </Grid>
</Page>
33
ответ дан Kris Erickson 7 November 2019 в 14:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: