- Home /
create line on a texture
hi there, my code to draw a line on a Texture2D is poor :\ do you have some hints ?
void drawLine(float x1, float y1, float x2, float y2){
float x,y;
float dy = y2-y1;
float dx = x2-x1;
float m = dy/dx;
float dy_inc = -1;
if( dy < 0 ) dy = 1;
float dx_inc = 1;
if( dx < 0 ) dx = -1;
if( Mathf.Abs(dy) > Mathf.Abs(dx) ){
for( y = y2; y < y1; y += dy_inc ){
x = x1 + ( y - y1 ) * m;
texture.SetPixel( (int)(x ) , (int)(y ), Color.clear );
}
}else{
for( x = x1; x < x2; x += dx_inc ) {
y = y1 + ( x - x1 ) * m;
texture.SetPixel( (int)(x ) , (int)(y ), Color.clear );
}
}
}
thanks
Answer by Syndias · Feb 06, 2016 at 10:35 AM
In case there is anyone still looking for a script that does this kind of thing:
public static void DrawLine(this Texture2D tex, Vector2 p1, Vector2 p2, Color col)
{
Vector2 t = p1;
float frac = 1/Mathf.Sqrt (Mathf.Pow (p2.x - p1.x, 2) + Mathf.Pow (p2.y - p1.y, 2));
float ctr = 0;
while ((int)t.x != (int)p2.x || (int)t.y != (int)p2.y) {
t = Vector2.Lerp(p1, p2, ctr);
ctr += frac;
tex.SetPixel((int)t.x, (int)t.y, col);
}
}
use it like this: (don't forget to call .apply())
public class LineDrawer : MonoBehaviour {
// Use this for initialization
void Start () {
Texture2D txr = new Texture2D (512, 512);
txr.DrawLine (new Vector2 (0, 0), new Vector2 (512, 256), Color.red);
txr.Apply ();
byte[] bytes = txr.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
}
}
Answer by JamesT · Feb 20, 2013 at 09:14 PM
I tested your code and it works with a few changes...
Make sure that the texture you are modifying was originally imported with Read/Write enabled (under advanced settings in the Inspector).
Be sure to call texture.Apply().
Here's an example showing the modifications I made...
//----------------------------------------------------------- using UnityEngine;
public class DrawLine : MonoBehaviour { public Texture2D MyTexture;
// Use this for initialization
void Start ()
{
Draw(0, 0, 100, 100);
renderer.material.mainTexture = MyTexture;
}
// Update is called once per frame
void Update ()
{
}
void Draw(float x1, float y1, float x2, float y2)
{
float x,y;
float dy = y2-y1;
float dx = x2-x1;
float m = dy/dx;
float dy_inc = -1;
if( dy < 0 )
dy = 1;
float dx_inc = 1;
if( dx < 0 )
dx = -1;
if( Mathf.Abs(dy) > Mathf.Abs(dx) )
{
for( y = y2; y < y1; y += dy_inc )
{
x = x1 + ( y - y1 ) * m;
Debug.Log("Setting Pixel at: x=" + x + ", y=" + y);
MyTexture.SetPixel((int)(x), (int)(y), Color.black);
}
}
else
{
for( x = x1; x < x2; x += dx_inc )
{
y = y1 + ( x - x1 ) * m;
Debug.Log("Setting Pixel at: x=" + x + ", y=" + y);
MyTexture.SetPixel((int)(x), (int)(y), Color.black);
}
}
MyTexture.Apply();
}
}
Your answer
Follow this Question
Related Questions
Drawing a solid circle onto texture 2 Answers
Drawing a Texture on top of another Texture 2 Answers
Positioning texture in a sphere 0 Answers