より良いエンジニアを目指して

1日1つ。良くなる!上手くなる!

PolylineにNaNを含むと描画されない

WPFで線のオブジェクトであるPolyLineは複数の点を指定します。

この複数点の中にNaNを含んだ場合、その線は描画されません。しかも、エラーにもなりません。

MainWindow.xaml

<Window x:Class="DrawZigZagLine.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:DrawZigZagLine"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="800">
    <Grid>
<Canvas x:Name="Canvas"/>
    </Grid>
</Window>

MainWindow.xaml.cs

#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

#endregion

namespace DrawZigZagLine
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            {
                var polyLine = new Polyline();
                var points = new PointCollection
                {
                    new Point(100, 100),
                    // NaN Point!!!
                    new Point(float.NaN,float.NaN),
                    new Point(700, 500)
                };
                polyLine.Points = points;
                polyLine.Stroke = Brushes.Red;
                Canvas.Children.Add(polyLine);
            }
        }
    }
}

f:id:rimever:20200812195119p:plain
描画されず真っ白。

そもそもfloat.NaNはどうして発生するか?

演算の結果が未定義の場合です。例として、0.0 / 0.0を紹介しています。

var a = 0F / 0F

docs.microsoft.com