简体   繁体   English

如何在统一的纹理上画圆圈?

[英]How to draw circle on texture in unity?

I try to find and show corners using opencv and unity3d. 我尝试使用opencv和unity3d查找和显示角落。 I capture by unity camera. 我通过统一相机拍摄。 I send texture2d to c++ code that uses opencv. 我将texture2d发送到使用opencv的c ++代码。 I detect corners using opencv(harris corner detector). 我使用opencv(哈里斯角探测器)探测角落。 And c++ code send to unity code corners points(x,y position on image). 并且c ++代码发送到统一代码角点(图像上的x,y位置)。

Finally, I want to show these points. 最后,我想展示这些观点。 I try to draw circle on texture2d in unity. 我试着在texture2d上统一绘制圆圈。 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 但是Unity说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? 如何在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. 只需为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 来自@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) (当我尝试在1000x1000纹理上绘制300个圆圈时,原始的一个减慢了我的电脑2分钟,而新的一个因为避免额外的迭代而立即执行)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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