How to draw circle on texture in unity?
Asked Answered
L

2

10

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;
Leghorn answered 23/5, 2015 at 7:52 Comment(5)
It's not that hardLeger
possible duplicate of How can I draw a circle in Unity3D?Leger
I find a project. It draws circle, line etc. here [github.com/ProtoTurtle/BitmapDrawingExampleProject]Leghorn
"I find a project. It draws circle, line etc. here [github.com/ProtoTurtle/BitmapDrawingExampleProject] " - if that's an answer it's a 404 page not found error sadlyLeger
remove last character in url, it is "]". try againLeghorn
C
11

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;
}
Catenary answered 16/6, 2019 at 6:55 Comment(1)
It's interesting that after 3 years I returned back to google with the same questionCatenary
K
5

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;
    }
}
Kameko answered 3/5, 2018 at 18:13 Comment(2)
Any idea how one would go about creating just the outline? Other than detecting nearby pixels?Trough
I figured it out. Draw another circle over top of it, but using clear, and smaller relative to the thickness you desire.Trough

© 2022 - 2024 — McMap. All rights reserved.