簡體   English   中英

如何在統一的紋理上畫圓圈?

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

我嘗試使用opencv和unity3d查找和顯示角落。 我通過統一相機拍攝。 我將texture2d發送到使用opencv的c ++代碼。 我使用opencv(哈里斯角探測器)探測角落。 並且c ++代碼發送到統一代碼角點(圖像上的x,y位置)。

最后,我想展示這些觀點。 我試着在texture2d上統一繪制圓圈。 我使用下面的代碼。 但是Unity說Type UnityEngine.Texture2D does not contain a definition for DrawCircle and no extension method DrawCircle of type UnityEngine.Texture2D could be found

如何在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;

只需為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;
    }
}

來自@ChrisH的更優化的解決方案
(當我嘗試在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