x


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

more ▼

asked Apr 25 '12 at 06:59 AM

erwin gravatar image

erwin
-5 1 3 3

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

I tested your code and it works with a few changes...

  1. Make sure that the texture you are modifying was originally imported with Read/Write enabled (under advanced settings in the Inspector).
  2. 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();
}

}

more ▼

answered Feb 20 at 09:14 PM

JamesT gravatar image

JamesT
2 3 4 5

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2188
x353
x122
x65

asked: Apr 25 '12 at 06:59 AM

Seen: 455 times

Last Updated: Feb 20 at 09:14 PM