4. 判斷 2 線段是否有相交
using System.Xml.XPath;
namespace Q4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
int x0 = -1, x1, y0, y1;
int x2 = -1, x3, y2, y3;
private void panel1_Paint(object sender, PaintEventArgs e)
{
var ml = 20;
var mt = 20;
//e.Graphics.DrawLine(new Pen(Brushes.Black), ml, midY, panel1.Width - ml, midY);
//e.Graphics.DrawLine(new Pen(Brushes.Black), midX, mt, midX, panel1.Height - mt);
e.Graphics.TranslateTransform(10, 10);
e.Graphics.ScaleTransform(8, 8);
var pen = new Pen(Brushes.Black);
pen.Width = .2f;
e.Graphics.DrawLine(pen, ax(-40), ay(0), ax(40), ay(0));
e.Graphics.DrawLine(pen, ax(0), ay(-30), ax(0), ay(30));
for (int y = -3; y <= 3; y++)
{
e.Graphics.FillEllipse(Brushes.Black, ax(-.5f), ay(.5f + (y) * 10), 1f, 1f);
}
for (int x = -4; x <= 4; x++)
{
e.Graphics.FillEllipse(Brushes.Black, ax(-.5f + x * 10), ay(.5f), 1f, 1f);
}
e.Graphics.DrawString("(-40,0)", new Font(FontFamily.GenericSansSerif, 1f), Brushes.Black, ax(-.5f + -40), ay(1f));
e.Graphics.DrawString("(40,0)", new Font(FontFamily.GenericSansSerif, 1f), Brushes.Black, ax(-.5f + 40), ay(1f));
e.Graphics.DrawString("(0,30)", new Font(FontFamily.GenericSansSerif, 1f), Brushes.Black, ax(1f), ay(-30f + .5f));
e.Graphics.DrawString("(0,-30)", new Font(FontFamily.GenericSansSerif, 1f), Brushes.Black, ax(1f), ay(29f + .5f));
if (x0 == -1) return;
MessageBox.Show(x0 + " " + x1 + " / " + y0 + " / " + y1);
e.Graphics.DrawLine(pen, ax(x0), ay(y0), ax(x1), ay(y1));
e.Graphics.DrawLine(pen, ax(x2), ay(y2), ax(x3), ay(y3));
// ax+by=c
// dx+ey=f
//N: (ce-bf)/(ae-bd)
//O: (cd-af)/(bd-ae)
// ax+by=c
// (y-y0)*(x1-x0) = (x-x0)*(y1-y0)
// -(y1-y0)*x + (x1-x0)*y = -(y1-y0)*x0+(x1-x0)*y0
double a = -(y1 - y0);
double b = x1 - x0;
double c = -(y1 - y0) * x0 + (x1 - x0) * y0;
double d = -(y3 - y2);
double ee = x3 - x2;
double f = -(y3 - y2) * x2 + (x3 - x2) * y2;
double N = (c * ee - b * f) / (a * ee - b * d);
double O = (c * d - a * f) / (b * d - a * ee);
textBox6.Text = "";
bool inst = (O >= y0 && O <= y1|| O >= y2 && O <= y3) ||
(N >= x2 && N <= x3 || N >= x0 && N <= x1);
textBox5.Text = inst ? "有相交" : "未相交";
//if (inst)
textBox6.Text = $"{N:0.##},{O:0.##}";
}
float ax(float x)
{
return x + 40;
}
float ay(float y)
{
return -y + 30;
}
private void button2_Click(object sender, EventArgs e)
{
x0 = -1;
panel1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
var l10 = textBox1.Text.Split(",").Select(int.Parse).ToList();
var l11 = textBox2.Text.Split(",").Select(int.Parse).ToList();
var l20 = textBox3.Text.Split(",").Select(int.Parse).ToList();
var l21 = textBox4.Text.Split(",").Select(int.Parse).ToList();
x0 = l10[0];
y0 = l10[1];
x1 = l11[0];
y1 = l11[1];
x2 = l20[0];
y2 = l20[1];
x3 = l21[0];
y3 = l21[1];
panel1.Refresh();
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
}
}
}
Last updated