Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw circle on texture in unity?

I try to find and show corners using opencv and unity3d. I capture by unity camera. I send texture2d to c++ code that uses opencv. I detect corners using opencv(harris corner detector). And c++ code send to unity code corners points(x,y position on image).

Finally, I want to show these points. I try to draw circle on texture2d in unity. I use below code. But unity says that Type UnityEngine.Texture2D does not contain a definition for DrawCircle and no extension method DrawCircle of type UnityEngine.Texture2D could be found

How can I draw simple shape on unity3d?

    Texture2D texture = new Texture2D(w, h,TextureFormat.RGB24 , false);
    texture.DrawCircle(100, 100, 20, Color.green);
    // Apply all SetPixel calls
    texture.Apply();
    mesh_renderer.material.mainTexture = texture;
like image 703
zakjma Avatar asked May 23 '15 07:05

zakjma


2 Answers

More optimized solution from @ChrisH
(Original one slowed down my pc for 2 minutes when I tried to draw 300 circles on 1000x1000 texture while new one does it immediately due to avoiding extra iterations)

public static Texture2D DrawCircle(this Texture2D tex, Color color, int x, int y, int radius = 3)
{
    float rSquared = radius * radius;

    for (int u = x - radius; u < x + radius + 1; u++)
        for (int v = y - radius; v < y + radius + 1; v++)
            if ((x - u) * (x - u) + (y - v) * (y - v) < rSquared)
                tex.SetPixel(u, v, color);

    return tex;
}
like image 166
IC_ Avatar answered Sep 24 '22 00:09

IC_


Just make an extension method for Texture2d.

public static class Tex2DExtension
{
    public static Texture2D Circle(this Texture2D tex, int x, int y, int r, Color color)
    {
        float rSquared = r * r;

        for (int u=0; u<tex.width; u++) {
            for (int v=0; v<tex.height; v++) {
                if ((x-u)*(x-u) + (y-v)*(y-v) < rSquared) tex.SetPixel(u,v,color);
            }
        }

        return tex;
    }
}
like image 36
Chris H Avatar answered Sep 25 '22 00:09

Chris H