Unity3d ugui coordinates to screen coordinates

As in the question
, a coordinate on the GUI is known. Find the coordinate of the coordinate in the Screen.
Unity's built-in function only has the method RectTransformUtility.ScreenPointToLocalPointInRectangle, which converts screen coordinates to ui coordinates, and there is no reverse evaluation method.
Insert picture description here
Application scenario:
opencv face recognition, the return value of the face recognition is the Rect array, Rect (face ui coordinate x, face ui coordinate y, face rectangular frame width, face rectangular frame height).
I asked for the position of the center point of this face on the screen, so I have this post.

Popularization of Unity coordinate system knowledge:
Unity coordinate system
Understand deduction 1. If you don’t understand, close the post.
Step into the topic: Knowing a coordinate in the GUI is converted to the Screen coordinate.
Insert picture description here
Prerequisite: The center coordinate of the picture is (0,0).
Find the screen coordinate of the blue point M. 1.
The gui coordinate K of the M point, (A.x+rectangular frame width/ 2. A.y+rectangular frame height
/2)=(167+183/2,210+183/2)=(258.5,301.5) 2. The center point of the screen coordinates L (1920/2,1080/2)=(960,540)
3. Determine whether the x of the M point is in the left half or the right half of the picture. If Kx>512/2 is true, then K is on the right half, and the corresponding screen abscissa is L.x+(Kx-512/2), if it is If false, K is in the left half, and the corresponding screen abscissa is Lx-(512/2-Kx)
4. Determine whether the y of point M is in the upper half or the lower half of the picture, and if Ky>1024/2 is true, K is below Half side, the corresponding screen ordinate is Ly-(Ky-1024/2), if it is false, K is on the left half, and the corresponding screen abscissa is L.y+(1024/2-Kx)

Look at the code:

    /// <summary>
    /// gui坐标转屏幕坐标
    /// </summary>
    /// <param name="rectTrans">图片的rectTrans</param>
    /// <param name="rect"></param>
    /// <returns></returns>
    Vector2 UiCenterPosToScreenPos(RectTransform rectTrans, OpenCVForUnity.Rect rect)
    {
    
    
        Vector2 scrPos;
        float uiCenterX = (rect.x + rect.width / 2) > (rectTrans.rect.width / 2) ? ((float)Screen.width / 2) + ((rect.x + rect.width / 2) - (rectTrans.rect.width / 2)) : ((float)Screen.width / 2) - ((rectTrans.rect.width / 2) - (rect.x + rect.width / 2));
        scrPos.x = uiCenterX;
        float uiCenterY = (rect.y + rect.height / 2) > (rectTrans.rect.height / 2) ? (((float)Screen.height / 2) - ((rect.y + rect.height / 2) - (rectTrans.rect.height / 2))) : (((float)Screen.height / 2) + ((rectTrans.rect.height / 2) - (rect.y + rect.height / 2)));
        scrPos.y = uiCenterY;
        return scrPos;
    }

Guess you like

Origin blog.csdn.net/gheartsea/article/details/108442851