Code 39 是常見的一維條碼規格,支援 43 個字元(0-9、A-Z、-、.、$、/、+、%、空格),以 * 作為起止碼。本文提供一個 WPF 範例,示範如何即時將文字轉換為 Code 39 條碼圖形。
Canvas。<Window x:Class="Code39Demo.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Title="Code 39 產生器" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Name="Textbox1" VerticalContentAlignment="Center"
TextChanged="Textbox1_TextChanged"/>
<Canvas Name="Canvas1" Grid.Row="1"/>
</Grid>
</Window>
0: ▮▮▯▯▮▯▯▮▯)。*。Canvas 上繪製黑白相間的 Rectangle。private void DrawBarcode(string input)
{
Canvas1.Children.Clear();
if (string.IsNullOrEmpty(input)) return;
string encoded = "*" + input.ToUpper() + "*";
double x = 0;
const double narrow = 2, wide = 6, height = 100;
foreach (char c in encoded)
{
if (!CharMap.TryGetValue(c, out string pattern)) continue;
foreach (char bar in pattern)
{
bool isBlack = bar == 'b';
double w = (bar == 'w' || bar == 'W') ? wide : narrow; // 簡化示意
var rect = new Rectangle
{
Width = w,
Height = height,
Fill = isBlack ? Brushes.Black : Brushes.White
};
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, 0);
Canvas1.Children.Add(rect);
x += w;
}
x += narrow; // 字元間距
}
}
Checksum 計算(Code 39 可選)。RenderTargetBitmap 存檔或列印。完整原始碼可參考 GitHub 專案 Code39Demo,已包含字元對照表與完整繪製邏輯。