679
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 多边形相交
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.HighQuality;
using (var p1 = new GraphicsPath())
{
p1.AddPolygon(new PointF[] { new PointF(10, 20), new PointF(80, 160), new PointF(200, 25)});
g.DrawPath(Pens.Green, p1);
var p2 = new GraphicsPath();
p2.AddPolygon(new PointF[] { new PointF(210, 200), new PointF(100, 100), new PointF(220, 30) });
g.DrawPath(Pens.Red, p2);
var box1 = p1.GetBounds();
var box2 = p2.GetBounds();
if (box1.IntersectsWith(box2))
{
var pen1 = new Pen(Color.Green, 1);
pen1.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
pen1.DashPattern = new float[] { 5, 5 };
g.DrawRectangle(pen1, box1.X, box1.Y, box1.Width, box1.Height);
var pen2 = new Pen(Color.Red, 1);
pen2.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
pen2.DashPattern = new float[] { 5, 5 };
g.DrawRectangle(pen2, box2.X, box2.Y, box2.Width, box2.Height);
var box3 = RectangleF.Intersect(box1, box2);
var pen3 = new Pen(Color.Black, 3);
pen3.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
pen3.DashPattern = new float[] { 1, 1 };
g.DrawRectangle(pen3, box3.X, box3.Y, box3.Width, box3.Height);
}
}
}
}
}
private bool pointInPolygon(float x, float y, PointF[] polygon)
{
int i;
int j = polygon.Length - 1;
bool oddNodes = false;
for (i = 0; i < polygon.Length; i++)
{
if ((polygon[i].Y < y && polygon[j].Y >= y || polygon[j].Y < y && polygon[i].Y >= y)
&& (polygon[i].X <= x || polygon[j].X <= x))
{
if (polygon[i].X + (y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < x)
{
oddNodes = !oddNodes;
}
}
j = i;
}
return oddNodes;
}
判断多边形、线段是否和另一多边形相交,可先判断他们的控制矩形是否相交 RectangleF.IntersectsWith 方法
更可以用 RectangleF.IntersectsWith 取回控制举行的交集
然后再做 点是否在多边形中的判断
用 GraphicsPath.IsVisible 可能更快