Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
En la mayoría de los casos, cuando se agrega adorno a cadenas de texto en la aplicación Windows Presentation Foundation (WPF), se usa texto en términos de una colección de caracteres discretos o glifos. Por ejemplo, podría crear un pincel de degradado lineal y aplicarlo a la Foreground propiedad de un TextBox objeto . Al mostrar o editar el cuadro de texto, el pincel de degradado lineal se aplica automáticamente al conjunto actual de caracteres de la cadena de texto.
Sin embargo, también puede convertir texto en Geometry objetos, lo que le permite crear otros tipos de texto visualmente enriquecido. Por ejemplo, podría crear un Geometry objeto basado en el esquema de una cadena de texto.
Cuando el texto se convierte en un Geometry objeto, ya no es una colección de caracteres; no se pueden modificar los caracteres de la cadena de texto. Sin embargo, puede afectar a la apariencia del texto convertido modificando sus propiedades de trazo y relleno. El trazo hace referencia al contorno del texto convertido; el relleno hace referencia al área dentro del contorno del texto convertido.
En los ejemplos siguientes se muestran varias formas de crear efectos visuales modificando el trazo y el relleno del texto convertido.
También es posible modificar el rectángulo delimitador, o resaltado, del texto convertido. En el ejemplo siguiente se muestra una manera de crear efectos visuales modificando el trazo y resaltado del texto convertido.
Ejemplo
La clave para convertir texto en un Geometry objeto es usar el FormattedText objeto . Una vez creado este objeto, puede usar los BuildGeometry métodos y BuildHighlightGeometry para convertir el texto en Geometry objetos. El primer método devuelve la geometría del texto con formato; el segundo método devuelve la geometría del cuadro de límite del texto con formato. En el ejemplo de código siguiente se muestra cómo crear un objeto FormattedText y obtener las geometrías del texto con formato y su cuadro de límite.
/// <summary>
/// Create the outline geometry based on the formatted text.
/// </summary>
public void CreateText()
{
System.Windows.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,
System.Windows.Media.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 System.Windows.Point(0, 0));
// Build the geometry object that represents the text highlight.
if (Highlight == true)
{
_textHighLightGeometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));
}
}
''' <summary>
''' Create the outline geometry based on the formatted text.
''' </summary>
Public Sub CreateText()
Dim fontStyle As FontStyle = FontStyles.Normal
Dim fontWeight As FontWeight = FontWeights.Medium
If Bold = True Then
fontWeight = FontWeights.Bold
End If
If Italic = True Then
fontStyle = FontStyles.Italic
End If
' Create the formatted text based on the properties set.
Dim formattedText As 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))
' Build the geometry object that represents the text highlight.
If Highlight = True Then
_textHighLightGeometry = formattedText.BuildHighlightGeometry(New Point(0, 0))
End If
End Sub
Para mostrar los Geometry objetos recuperados, debe acceder al DrawingContext del objeto que muestra el texto convertido. En estos ejemplos de código, este acceso se logra mediante la creación de un objeto de control personalizado derivado de una clase que admite la representación definida por el usuario.
Para mostrar Geometry objetos en el control personalizado, implemente una sobrecarga para el método OnRender. El método invalidado debe usar el DrawGeometry método para dibujar los Geometry objetos.
/// <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)
{
// Draw the outline based on the properties that are set.
drawingContext.DrawGeometry(Fill, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textGeometry);
// Draw the text highlight based on the properties that are set.
if (Highlight == true)
{
drawingContext.DrawGeometry(null, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textHighLightGeometry);
}
}
''' <summary>
''' OnRender override draws the geometry of the text and optional highlight.
''' </summary>
''' <param name="drawingContext">Drawing context of the OutlineText control.</param>
Protected Overrides Sub OnRender(ByVal drawingContext As DrawingContext)
' Draw the outline based on the properties that are set.
drawingContext.DrawGeometry(Fill, New Pen(Stroke, StrokeThickness), _textGeometry)
' Draw the text highlight based on the properties that are set.
If Highlight = True Then
drawingContext.DrawGeometry(Nothing, New Pen(Stroke, StrokeThickness), _textHighLightGeometry)
End If
End Sub
Para obtener el origen del objeto de control de usuario personalizado de ejemplo, vea OutlineTextControl.cs para C# y OutlineTextControl.vb para Visual Basic.
Consulte también
.NET Desktop feedback