I have been working to create a freeform cropping tool using Unity's Texture2D
class and the mask component. Till now I have created a system with which a user can draw a freeform shape on a transparent image. I need an algorithm with which I will be able to identify and fill the portion which is inside the drawn region.
Till now I have implemented the following approaches
- I used this logic to identify if a point was between the drawn shape but this doesn't work for freeform drawn shapes https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/
int count;
int a = 0;
for (int x = 0; x < image_width; x++)
{
count = 0;
for (int y = 0; y < image_height-1; y++)
{
if (drawingLayerTexture.GetPixel(x, y) == Color.red && drawingLayerTexture.GetPixel(x, y + 1) != Color.red)
{
count++;
}
}
if(drawingLayerTexture.GetPixel(x,image_height)==Color.red)
{
count++;
}
if (count > 1)
{
count = 0;
for (int y = 0; y < image_height-1; y++)
{
if (drawingLayerTexture.GetPixel(x, y) == Color.red && drawingLayerTexture.GetPixel(x, y + 1) != Color.red)
{
count++;
}
if (count % 2 == 1)
{
drawingLayerTexture.SetPixel(x, y, Color.white);
a++;
}
}
}
}
- Instead of checking only for a line, I checked the point above and besides the point but it still doesn't work for all cases
// Red is the color of the freeform shape drawn by the user, White is the region which is inside the shape
for(int y=0;y<image_height;y++)
{
for(int x=0;x<image_width;x++)
{
if (drawingLayerTexture.GetPixel(x, y) == Color.red)
drawingLayerTexture.SetPixel(x, y, Color.white);
else if (x == 0 || y == 0)
continue;
else if ((drawingLayerTexture.GetPixel(x - 1, y) == Color.white) && (drawingLayerTexture.GetPixel(x, y - 1) == Color.white))
drawingLayerTexture.SetPixel(x, y, Color.white);
}
}
The region identified(incorrect)
Even though I understand why each of these approaches doesn't work, I can't think of a correct algorithm