- Home /
How do I convert a Vector2 from a UV coordinate to an absolute pixel position?
Im working on something where Im extracting UV points from a mesh and trying to draw them onto a Texture2D and reverse the UV mapping process. Like, I want to get the UVs from a mesh and recreate the UV Wireframe map. As we all know UVs are store in percentage, but for the life of me (maybe just a brain fart kind of day) what formula can I use to convert that to an absolute pixel point. Assuming that Im drawing on a 512x512 Texture2D...
Thanks!
Well, I was able to extract a UV wireframe sort of... But it was not what I was expecting to say the least. I took the UV coordinates from my mesh, and drew lines from one to the next, but I guess what I did't account for is that I really have no idea when one starts and another ends. Any advice on recreating a UV wireframe from the $$anonymous$$esh UVs?

Well, you don't simply draw lines from one to the next ;) You have to iterate through your triangles array. 3 indices define one triangle. You get 3 UV coordinates with those 3 indices. Just draw each line of the triangle.
 //C# - pseudocode
 int[] triangles = mesh.triangles;
 Vector2[] uvs = mesh.uv;
 
 for(int i = 0; i < triangles.Length; i+=3)
 {
     var p1 = uvs[triangles[i + 0]];
     var p2 = uvs[triangles[i + 1]];
     var p3 = uvs[triangles[i + 2]];
     DrawLine(p1,p2);
     DrawLine(p2,p3);
     DrawLine(p3,p1);
 }
btw: For UV viewers it's more common to repeat the unterlying texture and just draw the UVs as they are (of course multiplied by the texture size but not wrapped "manually"). I wrote an EditorWindow some time ago that did this, but can't find it at the moment ;)
Ahhhhhh, that makes much more sense now that you think about it. I suppose this will work as long as your mesh does not share UV space, but that's a problem for another day :)
Answer by DMGregory · May 20, 2014 at 10:03 PM
The simplest case:
 int texelX = Mathf.FloorToInt(uv.x * textureWidth);
 int texelY = Mathf.FloorToInt(uv.y * textureHeight);
With a few caveats:
- this does not take into account wrapping/clamping for coordinates outside the [0, 1] range. You can get this with modulo (%) or Mathf.Clamp, respectively. 
- the y direction may be flipped relative to what you expect. TextureHeight - texelY - 1 may be what you want instead, depending on your setup. 
- I don't think DirectX 9's half-pixel offset applies in this case, but if you find your answers are one pixel off you may need to add +0.5f inside each of the floors above. 
Your answer
 
 
             Follow this Question
Related Questions
How should I convert Vector2 Coordinates to UV Coordinates? 1 Answer
Understanding verts and triangles in Unity 1 Answer
Mesh UV min/max Y position 2 Answers
Texturing procedurally generated geometry 0 Answers
uv sub meshes in cube c# 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                