前提・実現したいこと
C#(WPF)にて、Canvas上にPathGeometryを表示させ、
その上からフリーハンドで線が描ける簡単なお絵かきアプリを作成しています。
発生している問題・エラーメッセージ
Path要素をそのままCanvasに描画すると図形が大きく入りきらないため、
viewbox(300,300)の子要素としてCanvas(3000,3000)を配置してみました。
その結果、PathのFill要素に何かしらの色を指定した際に
NullReferenceExceptionが発生してしまうようになりました。
(下記ソースのpath.Fill = Brushes.Black;をコメントアウトすると正常動作)
Fillプロパティに色を指定しつつ、問題に対処する方法についてお心当たりのある方のご指摘をお待ちしております。
【MyPolyline.Points.Add(e.GetPosition(canvas));にて発生】 System.NullReferenceException: 'オブジェクト参照がオブジェクト インスタンスに設定されていません。' MyPolyline が null でした。
該当のソースコード
xaml
1 <Grid> 2 <Viewbox Name="viewbox" Height="300" Width="300" Stretch="Uniform" > 3 <Canvas Name="canvas" HorizontalAlignment="Stretch" Height="3000" VerticalAlignment="Stretch" Width="3000" Background="Transparent" MouseLeftButtonDown="canvas_MouseLeftButtonDown" MouseLeftButtonUp="canvas_MouseLeftButtonUp" MouseMove="canvas_MouseMove" > 4 </Canvas> 5 </Viewbox> 6 </Grid>
C#
1namespace CanvasTest 2{ 3 /// <summary> 4 /// MainWindow.xaml の相互作用ロジック 5 /// </summary> 6 public partial class MainWindow : Window 7 { 8 bool IsDrawing = false; 9 Polyline MyPolyline; 10 List<Polyline> MyListPolyline = new List<Polyline>(); 11 12 public MainWindow() 13 { 14 InitializeComponent(); 15 16 System.Windows.Shapes.Path path = new System.Windows.Shapes.Path(); 17 var data = "M0 00 H 5000 V 5000 H 100 L 100 100"; 18 var geometry = Geometry.Parse(data); 19 var pathgeometry = PathGeometry.CreateFromGeometry(geometry); 20 path.Data = pathgeometry; 21 path.Stroke = Brushes.Black; 22 path.Fill = Brushes.Black; 23 canvas.Children.Add(path); 24 25 26 canvas.MouseMove += canvas_MouseMove; 27 canvas.MouseLeftButtonDown += canvas_MouseLeftButtonDown; 28 canvas.MouseLeftButtonUp += canvas_MouseLeftButtonUp; 29 } 30 31 private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) 32 { 33 if (IsDrawing == true) 34 { 35 IsDrawing = false; 36 canvas.ReleaseMouseCapture(); 37 MyPolyline.Tag = MyPolyline.Points; 38 39 if (MyPolyline.Points.Count == 0) 40 { 41 MyListPolyline.Remove(MyPolyline); 42 canvas.Children.Remove(MyPolyline); 43 } 44 } 45 } 46 47 private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 48 { 49 IsDrawing = true; 50 canvas.CaptureMouse(); 51 MyPolyline = new Polyline(); 52 MyPolyline.Stroke = Brushes.Blue; 53 MyPolyline.StrokeThickness = 20; 54 MyPolyline.StrokeLineJoin = PenLineJoin.Round; 55 MyListPolyline.Add(MyPolyline); 56 canvas.Children.Add(MyPolyline); 57 } 58 59 private void canvas_MouseMove(object sender, MouseEventArgs e) 60 { 61 if (e.LeftButton == MouseButtonState.Pressed && IsDrawing == true) 62 { 63 MyPolyline.Points.Add(e.GetPosition(canvas)); 64 } 65 } 66 } 67}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/30 02:47
2018/09/30 06:24
2018/09/30 06:46