儲存TextBox中的文字為Path功能
今天再設計一個我自己程式的Icon時使用了Path+textbox做了圖形,我不想導出為PNG,因為顔色比較單一,我又想通過代碼控制顔色,是以我想完整的儲存為Path。是以做了這個軟體,支援設定不同的字型和字号,然後點選擷取Path,就導出了path。然後粘貼到想用的地方即可。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLKJ2MQRUcSJ3ZzJENUVTevwFMy8CX2AzLcFjMwIzLcRXZu5Sas9Gbuk2Lc9CX6MHc0RHaiojIsJye.png)
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
namespace TextTransformationPath
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
[Obsolete]
public string CreateText(string text)
{
System.Windows.FontStyle fontStyle = FontStyles.Normal;
FontWeight fontWeight = FontWeights.Medium;
var pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
FormattedText formattedText = new FormattedText(
text,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface(
new FontFamily(cbo_fontFamily.SelectedItem.ToString()),
fontStyle,
fontWeight,
FontStretches.Normal),
Convert.ToInt32(FontSizeTextBox.Text),
System.Windows.Media.Brushes.Black,
pixelsPerDip
);
// Build the geometry object that represents the text.
var _textGeometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));
// Build the geometry object that represents the text highlight.
var res = PathGeometry.CreateFromGeometry(_textGeometry).ToString();
return res;
}
private void GetTextTransformPath_Click(object sender, RoutedEventArgs e)
{
ResultPathTextBox.Text= CreateText(SourceText.Text);
}
}
}
XAML代碼
<Window x:Class="TextTransformationPath.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextTransformationPath"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBlock Margin="0,5" Text="輸入待擷取Path的内容:"/>
<TextBox FontSize="{Binding ElementName=FontSizeTextBox,Path=Text}" Height="50" x:Name="SourceText" Text="杜文龍" FontFamily="{Binding ElementName=cbo_fontFamily,Path=SelectedItem}"/>
<ComboBox x:Name="cbo_fontFamily" SelectedIndex="0" ItemsSource="{x:Static Fonts.SystemFontFamilies}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemsPanel >
<ItemsPanelTemplate >
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
<TextBlock Text="字号:"/>
<TextBox x:Name="FontSizeTextBox" Text="30"/>
<Button Margin="0,5" Content="點選擷取Path" Click="GetTextTransformPath_Click"/>
<TextBox x:Name="ResultPathTextBox"/>
</StackPanel>
</Grid>
</Window>