# draw line on texture

hi,

i found this function on the internet.
http://wiki.unity3d.com/index.php?title=TextureDrawLine

can someone help me to get a linewidth within this function?

the c# code on the website is wrong, so i already changed that.

``````void DrawLine(Texture2D a_Texture, int x1, int y1, int x2, int y2, int lineWidth, Color a_Color)
{
float xPix = x1;
float yPix = y1;

float width = x2 - x1;
float height = y2 - y1;
float length = Mathf.Abs(width);
if (Mathf.Abs(height) > length) length = Mathf.Abs(height);
int intLength = (int)length;
float dx = width / (float)length;
float dy = height / (float)length;
for (int i = 0; i <= intLength; i++)
{
a_Texture.SetPixel((int)xPix, (int)yPix, a_Color);

xPix += dx;
yPix += dy;
}
}
``````

Thanks!

Can’t help with the line width, but thanks for posting this! The line drawing works perfectly!

Your code may not be very efficient… usually the Bresenham algorithm is used to do the line-drawing calculation entirely with integers. Though with modern processors, I’m not sure that has the benefit it did in old days. It’d be interesting to benchmark it sometime.

Anyway, to draw thick lines efficiently is a bit tricky. Here are some good starting points.

If you don’t want to roll it yourself, you can probably find something in the Asset Store for drawing all sorts of things on a texture already. And if you can’t, let me know… I have some code lying around that I might clean up and assemble into just such an asset, if that really is an unfulfilled need.

Accessing the pixels of a texture is very inefficient. With Unity you have a full blown graphics engine at you disposition, so make use of it. It would much more efficient to draw directly to a RenderTexture by using meshes to draw your thick lines.

Edit:
You could even use the Unity Built-in LineRender this way.