简体   繁体   中英

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;

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;
    }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM