wpf 標尺 刻度尺 適用於影像縮放

dyfisgod發表於2024-12-02

xaml部分主要程式碼:

<Canvas x:Name="cvRuler" Margin="0" Background="WhiteSmoke" TextBlock.Foreground="Black"/>

後臺主要程式碼

 1         //畫標尺
 2         private void DrawRule()
 3         {
 4 
 5             if (cvRuler.Children != null)
 6             {
 7                 cvRuler.Children.Clear();
 8             }
 9 
10             System.Windows.Shapes.Line _line;
11             TextBlock _textBlock;
12             
13             var xScale =你的縮放倍數;
14 
15             int _lineIndex = 0;
16             double _width = cvRuler.ActualWidth;//展示部分總pixel
17             string _unit = "(cm)";
18             float _inch = (float)5195/600;//dpi為600時,對應總英寸
19             float _cm = (float)(_inch*2.54);//英寸換算成cm
20             double _pixelPerline = _width/_cm/10*xScale;//刻度尺每cm對應多少pixel。分成十份,再乘以縮放倍數
21             for (double i = 0; i < _width; i += _pixelPerline)
22             {
23                 _line = new System.Windows.Shapes.Line();
24                 _line.X1 = i;
25                 _line.X2 = i;
26                 _line.Y1 = 0;
27                 _line.StrokeThickness = 1;
28                 if (_lineIndex % 10 == 0)//十份,最長的刻度線
29                 {
30                     _line.Stroke = Brushes.DimGray;
31                     _line.Y2 = 25;
32 
33                     _textBlock = new TextBlock();
34                     _textBlock.Text = (_lineIndex/10).ToString()+(_lineIndex==0 ? _unit : "");
35                     _textBlock.FontSize = 8;
36                     _textBlock.HorizontalAlignment = HorizontalAlignment.Left;
37                     _textBlock.VerticalAlignment = VerticalAlignment.Top;
38                     _textBlock.Margin = new Thickness(i+2, 20, 0, 0);
39                     cvRuler.Children.Add(_textBlock);
40                 }
41                 else if (_lineIndex % 5 == 0)//中間的刻度線
42                 {
43                     _line.Stroke = Brushes.Gray;
44                     _line.Y2 = 20;
45                 }
46                 else
47                 {
48                     _line.Stroke = Brushes.Gray;
49                     _line.Y2 = 15;
50                 }
51                 cvRuler.Children.Add(_line);
52 
53                 _lineIndex++;
54             }
55         }

相關文章