I am trying to find a line is intersecting a circle or not.
I write code but seems some issues with that code.
private Point2d[] IntersectionPoint(Point2d p1, Point2d p2, Point2d sc, double r)
{
Point2d[] sect = null;
double a, b, c;
double bb4ac;
double mu1, mu2;
Point2d dp;
dp = p2 - p1;
a = dp.X * dp.X + dp.Y * dp.Y;
b = 2 * (dp.X * (p1.X - sc.X) + dp.Y * (p1.Y - sc.Y));
c = sc.X * sc.X + sc.Y * sc.Y;
c += p1.X * p1.X + p1.Y * p1.Y;
c -= 2 * (sc.X * p1.X + sc.Y * p1.Y);
c -= r * r;
bb4ac = b * b - 4 * a * c;
if (Math.Abs(a) < Double.Epsilon || bb4ac < 0)
{
return new Point2d[0];
}
mu1 = (-b + Math.Sqrt(bb4ac)) / (2 * a);
mu2 = (-b - Math.Sqrt(bb4ac)) / (2 * a);
// no intersection
if ((mu1 < 0 || mu1 > 1) && (mu2 < 0 || mu2 > 1))
{
sect = new Point2d[0];
}
// one point on mu1
else if (mu1 > 0 && mu1 < 1 && (mu2 < 0 || mu2 > 1))
{
sect = new Point2d[1];
sect[0] = p1 + ((p2 - p1) * mu1);
}
// one point on mu2
else if (mu2 > 0 && mu2 < 1 && (mu1 < 0 || mu1 > 1))
{
sect = new Point2d[1];
sect[0] = p1 + ((p2 - p1) * mu2);
}
// one or two points
else if (mu1 > 0 && mu1 < 1 && mu2 > 0 && mu2 < 1)
{
// tangential
if (mu1 == mu2)
{
sect = new Point2d[1];
sect[0] = p1 + ((p2 - p1) * mu1);
}
// two points
else
{
sect = new Point2d[2];
sect[0] = p1 + ((p2 - p1) * mu1);
sect[1] = p1 + ((p2 - p1) * mu2);
}
}
else
{
// should NEVER get here
sect = new Point2d[0];
}
return sect;
}
And calling this function like
Point ptOld = points[oldPoint];
Point ptNew = points[newPoint];
Point2d p1 = new Point2d((float)ptOld.latitude, (float)ptOld.longitude);
Point2d p2 = new Point2d((float)ptNew.latitude, (float)ptNew.longitude);
Point2d sc = new Point2d((float)loc.latitude, (float)loc.longitude);
It fails when i am trying with these co-ordinates
30,-30
80,-40
10
https://www.dropbox.com/s/38r9eylt2p4xfvw/graph.png
You could do some linear algebra:
Express the line as an origin point P1 and a normalized direction vector N
Project the center C of the circle onto the line: PC = P1 + dot(C - P1, N) * N
Compute the distance squared dSquared between points C and PC.
If equal (with some small tolerance) to radiusSquared, PC is on the circle and is the single intersection point.
If greater than radiusSquared, no intersection.
Otherwise, the two intersections are given by
offset = sqrt(radiusSquared - dSquared).
Intersections = PC +/- offset * N.
Edit: Vectors are now available in C#.
There is my code for intersecting:
public static Vector3? IntersectRayCircle(Vector3 rayStart, Vector3 rayPoint, Vector3 circlePosition, float circleRadiusSquared)
{
if (rayStart == rayPoint || circleRadiusSquared <= 0)
{
return null;
}
Vector3 nearest = GetNearestPoint(circlePosition, rayStart, rayPoint, false, false);
float distanceSquared = Vector3.DistanceSquared(nearest, circlePosition);
if (distanceSquared > circleRadiusSquared)
{
return null;
}
Vector3 offset = Vector3.Normalize(rayPoint - rayStart) * (float)Math.Sqrt(circleRadiusSquared - distanceSquared);
if (Vector3.DistanceSquared(circlePosition, rayStart) < circleRadiusSquared)
{
return nearest + offset;
}
else
{
return nearest - offset;
}
}
public static Vector3 GetNearestPoint(Vector3 location, Vector3 segmentStart, Vector3 segmentEnd, bool trimStart, bool trimEnd)
{
if (segmentStart == segmentEnd)
{
throw new ArgumentException("segmentStart cannot be equal to segmentEnd.");
}
Vector3 AP = location - segmentStart;
Vector3 AB = segmentEnd - segmentStart;
float magnitudeAB = AB.LengthSquared();
float ABAPproduct = Vector3.Dot(AP, AB);
float distance = ABAPproduct / magnitudeAB;
return (distance < 0 && trimStart) ? segmentStart : (distance > 1 && trimEnd) ? segmentEnd : segmentStart + AB * distance;
}
So I am trying to translate the algorith found here for concave hulls: http://repositorium.sdum.uminho.pt/bitstream/1822/6429/1/ConcaveHull_ACM_MYS.pdf
(Page 65)
Ive read through the entire thing but I cant figure out how to implement sortByAngle and angle, im not to sure what method I should do inside of them. This is what I have so far:
//Main method
public static Vertex[] ConcaveHull(Vertex[] points, int k = 3)
{
if (k < 3)
throw new ArgumentException("K is required to be 3 or more", "k");
List<Vertex> hull = new List<Vertex>();
//Clean first, may have lots of duplicates
Vertex[] clean = RemoveDuplicates(points);
if (clean.Length < 3)
throw new ArgumentException("At least 3 dissimilar points reqired", "points");
if (clean.Length == 3)//This is the hull, its already as small as it can be.
return clean;
if (clean.Length < k)
throw new ArgumentException("K must be equal to or smaller then the amount of dissimilar points", "points");
Vertex firstPoint = clean[0]; //TODO find mid point
hull.Add(firstPoint);
Vertex currentPoint = firstPoint;
Vertex[] dataset = RemoveIndex(clean, 0);
double previousAngle = 0;
int step = 2;
int i;
while (((currentPoint != firstPoint) || (step == 2)) && (dataset.Length > 0))
{
if (step == 5)
dataset = Add(dataset, firstPoint);
Vertex[] kNearestPoints = nearestPoints(dataset, currentPoint, k);
Vertex[] cPoints = sortByAngle(kNearestPoints, currentPoint, previousAngle);
bool its = true;
i = 0;
while ((its) && (i < cPoints.Length))
{
i++;
int lastPoint = 0;
if (cPoints[0] == firstPoint)
lastPoint = 1;
int j = 2;
its = false;
while ((!its) && (j < hull.Count - lastPoint))
{
its = intersectsQ(hull[step - 1 - 1], cPoints[0], hull[step - i - j - 1], hull[step - j - 1]);
j++;
}
}
if (its)
{
return ConcaveHull(points, k + 1);
}
currentPoint = cPoints[0];
hull.Add(currentPoint);
previousAngle = angle(hull[step - 1], hull[step - 2]);
dataset = RemoveIndex(dataset, 0);
step++;
}
bool allInside = true;
i = dataset.Length;
while (allInside && i > 0)
{
allInside = new Polygon(dataset).Contains(currentPoint); //TODO havent finished ray casting yet.
i--;
}
if (!allInside)
return ConcaveHull(points, k + 1);
return hull.ToArray();
}
private static Vertex[] Add(Vertex[] vs, Vertex v)
{
List<Vertex> n = new List<Vertex>(vs);
n.Add(v);
return n.ToArray();
}
private static Vertex[] RemoveIndex(Vertex[] vs, int index)
{
List<Vertex> removed = new List<Vertex>();
for (int i = 0; i < vs.Length; i++)
if (i != index)
removed.Add(vs[i]);
return removed.ToArray();
}
private static Vertex[] RemoveDuplicates(Vertex[] vs)
{
List<Vertex> clean = new List<Vertex>();
VertexComparer vc = new VertexComparer();
foreach (Vertex v in vs)
{
if (!clean.Contains(v, vc))
clean.Add(v);
}
return clean.ToArray();
}
private static Vertex[] nearestPoints(Vertex[] vs, Vertex v, int k)
{
Dictionary<double, Vertex> lengths = new Dictionary<double, Vertex>();
List<Vertex> n = new List<Vertex>();
double[] sorted = lengths.Keys.OrderBy(d => d).ToArray();
for (int i = 0; i < k; i++)
{
n.Add(lengths[sorted[i]]);
}
return n.ToArray();
}
private static Vertex[] sortByAngle(Vertex[] vs, Vertex v, double angle)
{
//TODO
return new Vertex[]{};
}
private static bool intersectsQ(Vertex v1, Vertex v2, Vertex v3, Vertex v4)
{
return intersectsQ(new Edge(v1, v2), new Edge(v3, v4));
}
private static bool intersectsQ(Edge e1, Edge e2)
{
double x1 = e1.A.X;
double x2 = e1.B.X;
double x3 = e2.A.X;
double x4 = e2.B.X;
double y1 = e1.A.Y;
double y2 = e1.B.Y;
double y3 = e2.A.Y;
double y4 = e2.B.Y;
var x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));
var y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));
if (double.IsNaN(x) || double.IsNaN(y))
{
return false;
}
else
{
if (x1 >= x2)
{
if (!(x2 <= x && x <= x1)) { return false; }
}
else
{
if (!(x1 <= x && x <= x2)) { return false; }
}
if (y1 >= y2)
{
if (!(y2 <= y && y <= y1)) { return false; }
}
else
{
if (!(y1 <= y && y <= y2)) { return false; }
}
if (x3 >= x4)
{
if (!(x4 <= x && x <= x3)) { return false; }
}
else
{
if (!(x3 <= x && x <= x4)) { return false; }
}
if (y3 >= y4)
{
if (!(y4 <= y && y <= y3)) { return false; }
}
else
{
if (!(y3 <= y && y <= y4)) { return false; }
}
}
return true;
}
private static double angle(Vertex v1, Vertex v2)
{
// TODO fix
Vertex v3 = new Vertex(v1.X, 0);
if (Orientation(v3, v1, v2) == 0)
return 180;
double b = EuclideanDistance(v3, v1);
double a = EuclideanDistance(v1, v2);
double c = EuclideanDistance(v3, v2);
double angle = Math.Acos((Math.Pow(a, 2) + Math.Pow(b, 2) - Math.Pow(c, 2)) / (2 * a * b));
if (Orientation(v3, v1, v2) < 0)
angle = 360 - angle;
return angle;
}
private static double EuclideanDistance(Vertex v1, Vertex v2)
{
return Math.Sqrt(Math.Pow((v1.X - v2.X), 2) + Math.Pow((v1.Y - v2.Y), 2));
}
public static double Orientation(Vertex p1, Vertex p2, Vertex p)
{
double Orin = (p2.X - p1.X) * (p.Y - p1.Y) - (p.X - p1.X) * (p2.Y - p1.Y);
if (Orin > 0)
return -1;//Left
if (Orin < 0)
return 1;//Right
return 0;//Colinier
}
I know that there is a load of code here. But im not sure if I can show the context and what I have without it.
Other classes:
public class Polygon
{
private Vertex[] vs;
public Polygon(Vertex[] Vertexes)
{
vs = Vertexes;
}
public Polygon(Bounds bounds)
{
vs = bounds.ToArray();
}
public Vertex[] ToArray()
{
return vs;
}
public IEnumerable<Edge> Edges()
{
if (vs.Length > 1)
{
Vertex P = vs[0];
for (int i = 1; i < vs.Length; i++)
{
yield return new Edge(P, vs[i]);
P = vs[i];
}
yield return new Edge(P, vs[0]);
}
}
public bool Contains(Vertex v)
{
return RayCasting.RayCast(this, v);
}
}
public class Edge
{
public Vertex A = new Vertex(0, 0);
public Vertex B = new Vertex(0, 0);
public Edge() { }
public Edge(Vertex a, Vertex b)
{
A = a;
B = b;
}
public Edge(double ax, double ay, double bx, double by)
{
A = new Vertex(ax, ay);
B = new Vertex(bx, by);
}
}
public class Bounds
{
public Vertex TopLeft;
public Vertex TopRight;
public Vertex BottomLeft;
public Vertex BottomRight;
public Bounds() { }
public Bounds(Vertex TL, Vertex TR, Vertex BL, Vertex BR)
{
TopLeft = TL;
TopRight = TR;
BottomLeft = BL;
BottomRight = BR;
}
public Vertex[] ToArray()
{
return new Vertex[] { TopLeft, TopRight, BottomRight, BottomLeft };
}
}
public class Vertex
{
public double X = 0;
public double Y = 0;
public Vertex() { }
public Vertex(double x, double y)
{
X = x;
Y = y;
}
public static Vertex[] Convert(string vs)
{
vs = vs.Replace("[", "");
vs = vs.Replace("]", "");
string[] spl = vs.Split(';');
List<Vertex> nvs = new List<Vertex>();
foreach (string s in spl)
{
try
{
nvs.Add(new Vertex(s));
}
catch
{
}
}
return nvs.ToArray();
}
public static string Stringify(Vertex[] vs)
{
string res = "[";
foreach (Vertex v in vs)
{
res += v.ToString();
res += ";";
}
res = res.RemoveLastCharacter();
res += "]";
return res;
}
public static string ToString(Vertex[] array)
{
string res = "[";
foreach (Vertex v in array)
res += v.ToString() + ",";
return res.RemoveLastCharacter() + "]";
}
/*
//When x < y return -1
//When x == y return 0
//When x > y return 1
public static int Compare(Vertex x, Vertex y)
{
//To find lowest
if (x.X < y.X)
{
return -1;
}
else if (x.X == y.X)
{
if (x.Y < y.Y)
{
return -1;
}
else if (x.Y == y.Y)
{
return 0;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
*/
public static int CompareY(Vertex a, Vertex b)
{
if (a.Y < b.Y)
return -1;
if (a.Y == b.Y)
return 0;
return 1;
}
public static int CompareX(Vertex a, Vertex b)
{
if (a.X < b.X)
return -1;
if (a.X == b.X)
return 0;
return 1;
}
public double distance (Vertex b){
double dX = b.X - this.X;
double dY = b.Y - this.Y;
return Math.Sqrt((dX*dX) + (dY*dY));
}
public double slope (Vertex b){
double dX = b.X - this.X;
double dY = b.Y - this.Y;
return dY / dX;
}
public static int Compare(Vertex u, Vertex a, Vertex b)
{
if (a.X == b.X && a.Y == b.Y) return 0;
Vertex upper = new Vertex();
Vertex p1 = new Vertex();
Vertex p2 = new Vertex();
upper.X = (u.X + 180) * 360;
upper.Y = (u.Y + 90) * 180;
p1.X = (a.X + 180) * 360;
p1.Y = (a.Y + 90) * 180;
p2.X = (b.X + 180) * 360;
p2.Y = (b.Y + 90) * 180;
if(p1 == upper) return -1;
if(p2 == upper) return 1;
double m1 = upper.slope(p1);
double m2 = upper.slope(p2);
if (m1 == m2)
{
return p1.distance(upper) < p2.distance(upper) ? -1 : 1;
}
if (m1 <= 0 && m2 > 0) return -1;
if (m1 > 0 && m2 <= 0) return -1;
return m1 > m2 ? -1 : 1;
}
public static Vertex UpperLeft(Vertex[] vs)
{
Vertex top = vs[0];
for (int i = 1; i < vs.Length; i++)
{
Vertex temp = vs[i];
if (temp.Y > top.Y || (temp.Y == top.Y && temp.X < top.X))
{
top = temp;
}
}
return top;
}
}
Just a note on convention: you should start function names with upper case, and variables with lower case. In the function sortByAngle, you have a reference to the parameter angle and the function angle simultaneously.
Assuming Angle(...) is simply meant to calculate the angle between two points:
private static double Angle(Vertex v1, Vertex v2)
{
return Math.Atan2(v2.Y - v1.Y, v2.X - v1.X);
}
will give you the angle from v1 to v2, in radians between -pi and +pi. Do not mix degrees and radians. My suggestion is to always use radians, and only convert to degrees if necessary for human-readable output.
private static Vertex[] SortByAngle(Vertex[] vs, Vertex v, double angle)
{
List<Vertex> vertList = new List<Vertex>(vs);
vertList.Sort((v1, v2) => AngleDifference(angle, Angle(v, v1)).CompareTo(AngleDifference(angle, Angle(v, v2))));
return vertList.ToArray();
}
uses List.Sort to sort the vertices from greatest to least angle difference between the vertices point and itself, and angle. The order of v1 and v2 are swapped in the input tuple to sort descending, that is, greatest difference first. The difference between angles is calculated like so:
private static double AngleDifference(double a, double b)
{
while (a < b - Math.PI) a += Math.PI * 2;
while (b < a - Math.PI) b += Math.PI * 2;
return Math.Abs(a - b);
}
The first two lines ensure that the angles are not more than 180 degrees apart.
You have error in
private static Vertex[] nearestPoints(Vertex[] vs, Vertex v, int k)
{
Dictionary<double, Vertex> lengths = new Dictionary<double, Vertex>();
List<Vertex> n = new List<Vertex>();
double[] sorted = lengths.Keys.OrderBy(d => d).ToArray();
for (int i = 0; i < k; i++)
{
n.Add(lengths[sorted[i]]);
}
return n.ToArray();
}
according to code if you have several vertexes at the same distance, function returns only one. Since Dictionary uses unique keys.
BTW, did anyone finish this?
I don't have the time right now to read the paper, but I assume from my knowledge of conVEX hull algorithms that you're going around the points in a particular direction looking for the next point to link to.
If that's the case, "angle" would be the angle of the most recent line segment of the hull, and you want to sort the points by their angle from that line. Therefore you want to calculate the angles between a line (on the hull) and a set of lines (from the current point to each other point being considered). Whether the angles calculated are positive or negative depends upon whether you're going clockwise or anticlockwise. To calculate the angles, look at something like this:
Calculating the angle between two lines without having to calculate the slope? (Java)
Then just sort by the angles.
What about that?
private List<Vector> sortClockwiseFromCentroid(List<Vector> points, Vector center)
{
points = points.OrderBy(x => Math.Atan2(x.X - center.X, x.Y - center.Y)).ToList();
return points;
}
I think a little background will help before I get into my question. What I'm doing is creating my own small 2D physics library in xna, for fun nonetheless. This is also my first independent xna project, and my first time working with the 3D tools, so I may be doing things all wacky. Anyway, I'm currently making a triangle class in which the constructor takes three arbitrary points in the form of Vector2s. In the constructor I have to put these points in clockwise order (so they're not culled) and then find the texture coordinates they should correspond to (since I'm using VertexPositionTextures as my vertices). What I've got works, but it seems very long and complicated. I'm looking for any ways to shorten/simplify the code, which is this:
public PTriangle(Vector2 a, Vector2 b, Vector2 c)
: base()
{
//set up vertices
VertexPositionTexture[] vertices = new VertexPositionTexture[3];
//center vertices around origin
Vector2 center = new Vector2((a.X + b.X + c.X) / 3, (a.Y + b.Y + c.Y) / 3);
Vector2 newA = a - center;
Vector2 newB = b - center;
Vector2 newC = c - center;
//get angle of each vertex (clockwise from -x axis)
double angleA = MathHelper.Pi - Math.Atan((double)(newA.Y / newA.X));
double angleB = MathHelper.Pi - Math.Atan((double)(newB.Y / newB.X));
double angleC = MathHelper.Pi - Math.Atan((double)(newC.Y / newC.X));
if (newA.X < 0)
{
if (newA.Y < 0)
{
angleA += MathHelper.Pi;
}
else
{
angleA -= MathHelper.Pi;
}
}
if (newB.X < 0)
{
if (newB.Y < 0)
{
angleB += MathHelper.Pi;
}
else
{
angleB -= MathHelper.Pi;
}
}
if (newC.X < 0)
{
if (newC.Y < 0)
{
angleC += MathHelper.Pi;
}
else
{
angleC -= MathHelper.Pi;
}
}
//order vertices by angle
Vector2[] newVertices = new Vector2[3];
if (angleA < angleB && angleA < angleC)
{
newVertices[0] = newA;
if (angleB < angleC)
{
newVertices[1] = newB;
newVertices[2] = newC;
}
else
{
newVertices[1] = newC;
newVertices[2] = newB;
}
}
else if (angleB < angleA && angleB < angleC)
{
newVertices[0] = newB;
if (angleA < angleC)
{
newVertices[1] = newA;
newVertices[2] = newC;
}
else
{
newVertices[1] = newC;
newVertices[2] = newA;
}
}
else
{
newVertices[0] = newC;
if (angleA < angleB)
{
newVertices[1] = newA;
newVertices[2] = newB;
}
else
{
newVertices[1] = newB;
newVertices[2] = newA;
}
}
//set positions of vertices
vertices[0].Position = new Vector3(newVertices[0] + center, 0);
vertices[1].Position = new Vector3(newVertices[1] + center, 0);
vertices[2].Position = new Vector3(newVertices[2] + center, 0);
//get width and height of triangle
float minX = 0;
float minY = 0;
float maxX = 0;
float maxY = 0;
foreach (Vector2 vertex in newVertices)
{
if (vertex.X < minX)
{
minX = vertex.X;
}
else if (vertex.X > maxX)
{
maxX = vertex.X;
}
if (vertex.Y < minY)
{
minY = vertex.Y;
}
else if (vertex.Y > maxY)
{
maxY = vertex.Y;
}
}
float width = maxX - minX;
float height = maxY - minY;
//shift triangle so fits in quadrant IV, and set texture coordinates
for (int index = 0; index < newVertices.Length; ++index)
{
newVertices[index].X -= minX;
newVertices[index].Y -= minY;
vertices[index].TextureCoordinate = new Vector2(
newVertices[index].X / width,
1 - (newVertices[index].Y / height));
}
this.Vertices = vertices;
//set up indices
this.Indices = new short[] { 0, 1, 2 };
}
To put the 3 points in clockwise order, you can use counter-clockwise test (or left-turn test) to check the direction of the 3 points.
Pseudocode from Wikipedia
# Three points are a counter-clockwise turn if ccw > 0, clockwise if
# ccw < 0, and collinear if ccw = 0 because ccw is a determinant that
# gives the signed area of the triangle formed by p1, p2 and p3.
function ccw(p1, p2, p3):
return (p2.x - p1.x)*(p3.y - p1.y) - (p2.y - p1.y)*(p3.x - p1.x)
If the 3 points are counter-clockwise, you can just swap the last 2 points to make the 3 points clockwise order.
I want to create a GraphicsPath and a list of Points to form the outline of the non-transparent area of a bitmap. If needed, I can guarantee that each image has only one solid collection of nontransparent pixels. So for example, I should be able to record the points either clockwise or counter-clockwise along the edge of the pixels and perform a full closed loop.
The speed of this algorithm is not important. However, the efficiency of the resulting points is semi-important if I can skip some points to reduce in a smaller and less complex GraphicsPath.
I will list my current code below which works perfectly with most images. However, some images which are more complex end up with paths which seem to connect in the wrong order. I think I know why this occurs, but I can't come up with a solution.
public static Point[] GetOutlinePoints(Bitmap image)
{
List<Point> outlinePoints = new List<Point>();
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] originalBytes = new byte[image.Width * image.Height * 4];
Marshal.Copy(bitmapData.Scan0, originalBytes, 0, originalBytes.Length);
for (int x = 0; x < bitmapData.Width; x++)
{
for (int y = 0; y < bitmapData.Height; y++)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
outlinePoints.Add(p);
break;
}
}
}
for (int y = 0; y < bitmapData.Height; y++)
{
for (int x = bitmapData.Width - 1; x >= 0; x--)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
outlinePoints.Add(p);
break;
}
}
}
for (int x = bitmapData.Width - 1; x >= 0; x--)
{
for (int y = bitmapData.Height - 1; y >= 0; y--)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
outlinePoints.Add(p);
break;
}
}
}
for (int y = bitmapData.Height - 1; y >= 0; y--)
{
for (int x = 0; x < bitmapData.Width; x++)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
outlinePoints.Add(p);
break;
}
}
}
// Added to close the loop
outlinePoints.Add(outlinePoints[0]);
image.UnlockBits(bitmapData);
return outlinePoints.ToArray();
}
public static bool ContainsPoint(IEnumerable<Point> points, Point value)
{
foreach (Point p in points)
{
if (p == value)
return true;
}
return false;
}
And when I turn the points into a path:
GraphicsPath outlinePath = new GraphicsPath();
outlinePath.AddLines(_outlinePoints);
Here's an example showing what I want. The red outline should be an array of points which can be made into a GraphicsPath in order to perform hit detection, draw an outline pen, and fill it with a brush.
Like both of you desrcipt you just have to find the first non transparent point and afterward move along the none transparent pixels with a transparent neighbor.
Additionaly you'll have to save the point you've already visisted and how often you visited them or you'll end in same cases in an invinity loop. If the point doesn't have a neighbor which already was visited you must go back each point, in revered direction, until a unvisited point is available again.
That's it.
See revision history for old versions.
Changes:
Point.EMPTY was replaced by Point(-1,-1), or a non transparent pixel
in the upper left corner causes an invinityloop
Check for borderpoint at the image border
class BorderFinder {
int stride = 0;
int[] visited = null;
byte[] bytes = null;
PointData borderdata = null;
Size size = Size.Empty;
bool outside = false;
Point zeropoint = new Point(-1,-1);
public List<Point[]> Find(Bitmap bmp, bool outside = true) {
this.outside = outside;
List<Point> border = new List<Point>();
BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
stride = bmpdata.Stride;
bytes = new byte[bmp.Width * bmp.Height * 4];
size = bmp.Size;
Marshal.Copy(bmpdata.Scan0, bytes, 0, bytes.Length);
// Get all Borderpoint
borderdata = getBorderData(bytes);
bmp.UnlockBits(bmpdata);
List<List<Point>> regions = new List<List<Point>>();
//Loop until no more borderpoints are available
while (borderdata.PointCount > 0) {
List<Point> region = new List<Point>();
//if valid is false the region doesn't close
bool valid = true;
//Find the first borderpoint from where whe start crawling
Point startpos = getFirstPoint(borderdata);
//we need this to know if and how often we already visted the point.
//we somtime have to visit a point a second time because we have to go backward until a unvisted point is found again
//for example if we go int a narrow 1px hole
visited = new int[bmp.Size.Width * bmp.Size.Height];
region.Add(startpos);
//Find the next possible point
Point current = getNextPoint(startpos);
if (current != zeropoint) {
visited[current.Y * bmp.Width + current.X]++;
region.Add(current);
}
//May occure with just one transparent pixel without neighbors
if (current == zeropoint)
valid = false;
//Loop until the area closed or colsing the area wasn't poosible
while (!current.Equals(startpos) && valid) {
var pos = current;
//Check if the area was aready visited
if (visited[current.Y * bmp.Width + current.X] < 2) {
current = getNextPoint(pos);
visited[pos.Y * bmp.Width + pos.X]++;
//If no possible point was found, search in reversed direction
if (current == zeropoint)
current = getNextPointBackwards(pos);
} else { //If point was already visited, search in reversed direction
current = getNextPointBackwards(pos);
}
//No possible point was found. Closing isn't possible
if (current == zeropoint) {
valid = false;
break;
}
visited[current.Y * bmp.Width + current.X]++;
region.Add(current);
}
//Remove point from source borderdata
foreach (var p in region) {
borderdata.SetPoint(p.Y * bmp.Width + p.X, false);
}
//Add region if closing was possible
if (valid)
regions.Add(region);
}
//Checks if Region goes the same way back and trims it in this case
foreach (var region in regions) {
int duplicatedpos = -1;
bool[] duplicatecheck = new bool[size.Width * size.Height];
int length = region.Count;
for (int i = 0; i < length; i++) {
var p = region[i];
if (duplicatecheck[p.Y * size.Width + p.X]) {
duplicatedpos = i - 1;
break;
}
duplicatecheck[p.Y * size.Width + p.X] = true;
}
if (duplicatedpos == -1)
continue;
if (duplicatedpos != ((region.Count - 1) / 2))
continue;
bool reversed = true;
for (int i = 0; i < duplicatedpos; i++) {
if (region[duplicatedpos - i - 1] != region[duplicatedpos + i + 1]) {
reversed = false;
break;
}
}
if (!reversed)
continue;
region.RemoveRange(duplicatedpos + 1, region.Count - duplicatedpos - 1);
}
List<List<Point>> tempregions = new List<List<Point>>(regions);
regions.Clear();
bool connected = true;
//Connects region if possible
while (connected) {
connected = false;
foreach (var region in tempregions) {
int connectionpos = -1;
int connectionregion = -1;
Point pointstart = region.First();
Point pointend = region.Last();
for (int ir = 0; ir < regions.Count; ir++) {
var otherregion = regions[ir];
if (region == otherregion)
continue;
for (int ip = 0; ip < otherregion.Count; ip++) {
var p = otherregion[ip];
if ((isConnected(pointstart, p) && isConnected(pointend, p)) ||
(isConnected(pointstart, p) && isConnected(pointstart, p))) {
connectionregion = ir;
connectionpos = ip;
}
if ((isConnected(pointend, p) && isConnected(pointend, p))) {
region.Reverse();
connectionregion = ir;
connectionpos = ip;
}
}
}
if (connectionpos == -1) {
regions.Add(region);
} else {
regions[connectionregion].InsertRange(connectionpos, region);
}
}
tempregions = new List<List<Point>>(regions);
regions.Clear();
}
List<Point[]> returnregions = new List<Point[]>();
foreach (var region in tempregions)
returnregions.Add(region.ToArray());
return returnregions;
}
private bool isConnected(Point p0, Point p1) {
if (p0.X == p1.X && p0.Y - 1 == p1.Y)
return true;
if (p0.X + 1 == p1.X && p0.Y - 1 == p1.Y)
return true;
if (p0.X + 1 == p1.X && p0.Y == p1.Y)
return true;
if (p0.X + 1 == p1.X && p0.Y + 1 == p1.Y)
return true;
if (p0.X == p1.X && p0.Y + 1 == p1.Y)
return true;
if (p0.X - 1 == p1.X && p0.Y + 1 == p1.Y)
return true;
if (p0.X - 1 == p1.X && p0.Y == p1.Y)
return true;
if (p0.X - 1 == p1.X && p0.Y - 1 == p1.Y)
return true;
return false;
}
private Point getNextPoint(Point pos) {
if (pos.Y > 0) {
int x = pos.X;
int y = pos.Y - 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.Y > 0 && pos.X < size.Width - 1) {
int x = pos.X + 1;
int y = pos.Y - 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.X < size.Width - 1) {
int x = pos.X + 1;
int y = pos.Y;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.X < size.Width - 1 && pos.Y < size.Height - 1) {
int x = pos.X + 1;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.Y < size.Height - 1) {
int x = pos.X;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.Y < size.Height - 1 && pos.X > 0) {
int x = pos.X - 1;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.X > 0) {
int x = pos.X - 1;
int y = pos.Y;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
if (pos.X > 0 && pos.Y > 0) {
int x = pos.X - 1;
int y = pos.Y - 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
}
}
return zeropoint;
}
private Point getNextPointBackwards(Point pos) {
Point backpoint = zeropoint;
int trys = 0;
if (pos.X > 0 && pos.Y > 0) {
int x = pos.X - 1;
int y = pos.Y - 1;
if (ValidPoint(x, y) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.X > 0) {
int x = pos.X - 1;
int y = pos.Y;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.Y < size.Height - 1 && pos.X > 0) {
int x = pos.X - 1;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.Y < size.Height - 1) {
int x = pos.X;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.X < size.Width - 1 && pos.Y < size.Height - 1) {
int x = pos.X + 1;
int y = pos.Y + 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.X < size.Width - 1) {
int x = pos.X + 1;
int y = pos.Y;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.Y > 0 && pos.X < size.Width - 1) {
int x = pos.X + 1;
int y = pos.Y - 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
if (pos.Y > 0) {
int x = pos.X;
int y = pos.Y - 1;
if ((ValidPoint(x, y)) && HasNeighbor(x, y)) {
if (visited[y * size.Width + x] == 0) {
return new Point(x, y);
}
if (backpoint == zeropoint || trys > visited[y * size.Width + x]) {
backpoint = new Point(x, y);
trys = visited[y * size.Width + x];
}
}
}
return backpoint;
}
private bool ValidPoint(int x, int y) {
return (borderdata[y * size.Width + x]);
}
private bool HasNeighbor(int x, int y) {
if (y > 0) {
if (!borderdata[(y - 1) * size.Width + x]) {
return true;
}
} else if (ValidPoint(x, y)) {
return true;
}
if (x < size.Width - 1) {
if (!borderdata[y * size.Width + (x + 1)]) {
return true;
}
} else if (ValidPoint(x, y)) {
return true;
}
if (y < size.Height - 1) {
if (!borderdata[(y + 1) * size.Width + x]) {
return true;
}
} else if (ValidPoint(x, y)) {
return true;
}
if (x > 0) {
if (!borderdata[y * size.Width + (x - 1)]) {
return true;
}
} else if (ValidPoint(x, y)) {
return true;
}
return false;
}
private Point getFirstPoint(PointData data) {
Point startpos = zeropoint;
for (int y = 0; y < size.Height; y++) {
for (int x = 0; x < size.Width; x++) {
if (data[y * size.Width + x]) {
startpos = new Point(x, y);
return startpos;
}
}
}
return startpos;
}
private PointData getBorderData(byte[] bytes) {
PointData isborderpoint = new PointData(size.Height * size.Width);
bool prevtrans = false;
bool currenttrans = false;
for (int y = 0; y < size.Height; y++) {
prevtrans = false;
for (int x = 0; x <= size.Width; x++) {
if (x == size.Width) {
if (!prevtrans) {
isborderpoint.SetPoint(y * size.Width + x - 1, true);
}
continue;
}
currenttrans = bytes[y * stride + x * 4 + 3] == 0;
if (x == 0 && !currenttrans)
isborderpoint.SetPoint(y * size.Width + x, true);
if (prevtrans && !currenttrans)
isborderpoint.SetPoint(y * size.Width + x - 1, true);
if (!prevtrans && currenttrans && x != 0)
isborderpoint.SetPoint(y * size.Width + x, true);
prevtrans = currenttrans;
}
}
for (int x = 0; x < size.Width; x++) {
prevtrans = false;
for (int y = 0; y <= size.Height; y++) {
if (y == size.Height) {
if (!prevtrans) {
isborderpoint.SetPoint((y - 1) * size.Width + x, true);
}
continue;
}
currenttrans = bytes[y * stride + x * 4 + 3] == 0;
if(y == 0 && !currenttrans)
isborderpoint.SetPoint(y * size.Width + x, true);
if (prevtrans && !currenttrans)
isborderpoint.SetPoint((y - 1) * size.Width + x, true);
if (!prevtrans && currenttrans && y != 0)
isborderpoint.SetPoint(y * size.Width + x, true);
prevtrans = currenttrans;
}
}
return isborderpoint;
}
}
class PointData {
bool[] points = null;
int validpoints = 0;
public PointData(int length) {
points = new bool[length];
}
public int PointCount {
get {
return validpoints;
}
}
public void SetPoint(int pos, bool state) {
if (points[pos] != state) {
if (state)
validpoints++;
else
validpoints--;
}
points[pos] = state;
}
public bool this[int pos] {
get {
return points[pos];
}
}
}
I've modified GetOutlinePoints by adding a helper variable than verifies the position at which new points should be added.
The idea of the outline detection algorithm in your code is something like looking at the image while standing each of its edges and writing down all non-transparent pixels that are visible. It's ok, however, you always added pixels to the end of the collection, which caused issues. I've added a variable that remembers position of the last pixel visible from the previous edge and the current one and uses it to determine index where the new pixel should be added. I suppose it should work as long as the outline is continuous, but I suppose it is in your case.
I've tested it on several images and it seems to work correctly:
public static Point[] GetOutlinePoints(Bitmap image)
{
List<Point> outlinePoints = new List<Point>();
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] originalBytes = new byte[image.Width * image.Height * 4];
Marshal.Copy(bitmapData.Scan0, originalBytes, 0, originalBytes.Length);
//find non-transparent pixels visible from the top of the image
for (int x = 0; x < bitmapData.Width; x++)
{
for (int y = 0; y < bitmapData.Height; y++)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
outlinePoints.Add(p);
break;
}
}
}
//helper variable for storing position of the last pixel visible from both sides
//or last inserted pixel
int? lastInsertedPosition = null;
//find non-transparent pixels visible from the right side of the image
for (int y = 0; y < bitmapData.Height; y++)
{
for (int x = bitmapData.Width - 1; x >= 0; x--)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
{
if (lastInsertedPosition.HasValue)
{
outlinePoints.Insert(lastInsertedPosition.Value + 1, p);
lastInsertedPosition += 1;
}
else
{
outlinePoints.Add(p);
}
}
else
{
//save last common pixel from visible from more than one sides
lastInsertedPosition = outlinePoints.IndexOf(p);
}
break;
}
}
}
lastInsertedPosition = null;
//find non-transparent pixels visible from the bottom of the image
for (int x = bitmapData.Width - 1; x >= 0; x--)
{
for (int y = bitmapData.Height - 1; y >= 0; y--)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
{
if (lastInsertedPosition.HasValue)
{
outlinePoints.Insert(lastInsertedPosition.Value + 1, p);
lastInsertedPosition += 1;
}
else
{
outlinePoints.Add(p);
}
}
else
{
//save last common pixel from visible from more than one sides
lastInsertedPosition = outlinePoints.IndexOf(p);
}
break;
}
}
}
lastInsertedPosition = null;
//find non-transparent pixels visible from the left side of the image
for (int y = bitmapData.Height - 1; y >= 0; y--)
{
for (int x = 0; x < bitmapData.Width; x++)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
if (!ContainsPoint(outlinePoints, p))
{
if (lastInsertedPosition.HasValue)
{
outlinePoints.Insert(lastInsertedPosition.Value + 1, p);
lastInsertedPosition += 1;
}
else
{
outlinePoints.Add(p);
}
}
else
{
//save last common pixel from visible from more than one sides
lastInsertedPosition = outlinePoints.IndexOf(p);
}
break;
}
}
}
// Added to close the loop
outlinePoints.Add(outlinePoints[0]);
image.UnlockBits(bitmapData);
return outlinePoints.ToArray();
}
Update:
This algorithm won't work correctly for images that have outline parts not "visible" from any of the edges. See comments for suggested solutions. I'll try to post a code snippet later.
Update II
I've prepared another algorithm as described in my comments. It just crawls around the object and saves the outline.
First, it finds the first pixel of the outline using a method from the previous algorithm. Then, it looks throught the neighbouring pixels in clockwise order, find the first one that is transparent and then continues browsing, but looking for a non-transparent one. The first non-transparent pixel found is the next one in the outline. The loop continues until it goes around the whole object and gets back to the starting pixel.
public static Point[] GetOutlinePointsNEW(Bitmap image)
{
List<Point> outlinePoints = new List<Point>();
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
Point currentP = new Point(0, 0);
Point firstP = new Point(0, 0);
byte[] originalBytes = new byte[image.Width * image.Height * 4];
Marshal.Copy(bitmapData.Scan0, originalBytes, 0, originalBytes.Length);
//find non-transparent pixels visible from the top of the image
for (int x = 0; x < bitmapData.Width && outlinePoints.Count == 0; x++)
{
for (int y = 0; y < bitmapData.Height && outlinePoints.Count == 0; y++)
{
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
if (alpha != 0)
{
Point p = new Point(x, y);
outlinePoints.Add(p);
currentP = p;
firstP = p;
break;
}
}
}
Point[] neighbourPoints = new Point[] { new Point(-1, -1), new Point(0, -1), new Point(1, -1),
new Point(1, 0), new Point(1, 1), new Point(0, 1),
new Point(-1, 1), new Point(-1, 0) };
//crawl around the object and look for the next pixel of the outline
do
{
bool transparentNeighbourFound = false;
bool nextPixelFound = false;
int i;
//searching is done in clockwise order
for (i = 0; (i < neighbourPoints.Length * 2) && !nextPixelFound; ++i)
{
int neighbourPosition = i % neighbourPoints.Length;
int x = currentP.X + neighbourPoints[neighbourPosition].X;
int y = currentP.Y + neighbourPoints[neighbourPosition].Y;
byte alpha = originalBytes[y * bitmapData.Stride + 4 * x + 3];
//a transparent pixel has to be found first
if (!transparentNeighbourFound)
{
if (alpha == 0)
{
transparentNeighbourFound = true;
}
}
else //after a transparent pixel is found, a next non-transparent one is the next pixel of the outline
{
if (alpha != 0)
{
Point p = new Point(x, y);
currentP = p;
outlinePoints.Add(p);
nextPixelFound = true;
}
}
}
} while (currentP != firstP);
image.UnlockBits(bitmapData);
return outlinePoints.ToArray();
}
One thing to remember is that it does work IF object does NOT ends at the edge of the image (there has to be a transparent space between the object and each of the edges).
This can be easily done if you just make the image one line larger at each side before passing it to the GetOutlinePointsNEW method.
The scenario by the poster was one I just encountered. After applying the GetOutlinePointsNEW method above, I encountered an index issue when the non-transparent pixel is at the edge of the image causing the crawl to be outside the bounds of the image. Below is a managed code update that treats the out of bounds pixels as non-transparent when performing the crawl.
static public Point[] crawlerPoints = new Point[] { new Point(-1, -1), new Point(0, -1), new Point(1, -1),
new Point(1, 0), new Point(1, 1), new Point(0, 1),
new Point(-1, 1), new Point(-1, 0) };
private BitmapData _bitmapData;
private byte[] _originalBytes;
private Bitmap _bitmap; //this is loaded from an image passed in during processing
public Point[] GetOutlinePoints()
{
List<Point> outlinePoints = new List<Point>();
_originalBytes = new byte[_bitmap.Width * _bitmap.Height * 4];
_bitmapData = _bitmap.LockBits(new Rectangle(0, 0, _bitmap.Width, _bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(_bitmapData.Scan0, _originalBytes, 0, _originalBytes.Length);
GetFirstNonTransparentPoint(outlinePoints);
if (outlinePoints.Count > 0) { GetNonTransparentPoints(outlinePoints); }
_bitmap.UnlockBits(_bitmapData);
return outlinePoints.ToArray();
}
private void GetFirstNonTransparentPoint(List<Point> outlinePoints)
{
Point firstPoint = new Point(0, 0);
for (int x = 0; x < _bitmapData.Width; x++)
{
for (int y = 0; y < _bitmapData.Height; y++)
{
if (!IsPointTransparent(x, y))
{
firstPoint = new Point(x, y);
outlinePoints.Add(firstPoint);
break;
}
}
if (outlinePoints.Count > 0) { break; }
}
}
private void GetNonTransparentPoints(List<Point> outlinePoints)
{
Point currentPoint = outlinePoints[0];
do //Crawl counter clock-wise around the current point
{
bool firstTransparentNeighbourFound = false;
bool nextPixelFound = false;
for (int i = 0; (i < ApplicationVariables.crawlerPoints.Length * 2) && !nextPixelFound; ++i)
{
int crawlPosition = i % ApplicationVariables.crawlerPoints.Length;
if (!firstTransparentNeighbourFound) { firstTransparentNeighbourFound = IsCrawlPointTransparent(crawlPosition, currentPoint); }
else
{
if (!IsCrawlPointTransparent(crawlPosition, currentPoint))
{
outlinePoints.Add(new Point(currentPoint.X + ApplicationVariables.crawlerPoints[crawlPosition].X, currentPoint.Y + ApplicationVariables.crawlerPoints[crawlPosition].Y));
currentPoint = outlinePoints[outlinePoints.Count - 1];
nextPixelFound = true;
}
}
}
} while (currentPoint != outlinePoints[0]);
}
private bool IsCrawlPointTransparent(int crawlPosition, Point currentPoint)
{
int x = currentPoint.X + ApplicationVariables.crawlerPoints[crawlPosition].X;
int y = currentPoint.Y + ApplicationVariables.crawlerPoints[crawlPosition].Y;
if (IsCrawlInBounds(x, y)) { return IsPointTransparent(x, y); }
return true;
}
private bool IsCrawlInBounds(int x, int y)
{
return ((x >= 0 & x < _bitmapData.Width) && (y >= 0 & y < _bitmapData.Height));
}
private bool IsPointTransparent(int x, int y)
{
return _originalBytes[(y * _bitmapData.Stride) + (4 * x) + 3] == 0;
}