# Crop a texture procedurally

Is there a way to crop a texture having a list of triangles which represent the part to be kept?
For instance, I have a rectangular texture and I want to obtain a texture shaped by the triangle list I have.

## 1 Answer

I don't think you can have non-rectangular texture. But you could get a bounding box for the vertices and crop the texture with it. Just read the pixels inside the bounding box and write them to a new texture instance.

Vector2i min = triangleslist; // Assuming the list is integer Vector2 list
Vector2i max = triangleslist; // and the vertex positions are in pixels

foreach(var p in triangleslist) {
if(p.x < min.x)
min.x = p.x;

if(p.x > max.x)
max.x = p.x;

if(p.y < min.y)
min.y = p.y;

if(p.y > max.y)
max.y = p.y;
}

var size = max - min;
var texture = new Texture2D(size.x, size.y, TextureFormat.ARGB32, false);

for(int x = 0; x < size.x; x++) {
for(int y = 0; y < size.y; y++) {
texture.SetPixel(x, y, originalTexture.GetPixel(x + min.x, y + min.y);
}
}