Unity3d ugui坐标转屏幕坐标

如题
已知GUI上的一个坐标,求该坐标在Screen屏幕中的坐标。
Unity自带的函数只有屏幕坐标转ui坐标的方法RectTransformUtility.ScreenPointToLocalPointInRectangle,没有反向求值的方法。
在这里插入图片描述
应用场景:
opencv人脸识别,识别人脸返回值是Rect数组,Rect(脸部ui坐标x,脸部ui坐标y,脸部矩形框宽,脸部矩形框高)。
我要求出这个人脸的中心点在屏幕中的位置,所以就有了这个帖子。

Unity坐标系知识普及:
unity坐标系
看懂扣1。看不懂就关闭帖子吧。
步入正题:已知GUI内的一个坐标转Screen坐标
在这里插入图片描述
前提:图片的中心坐标为(0,0)
求蓝点M的屏幕坐标
1.M点的gui坐标K,(A.x+矩形框宽/2,A.y+矩形框高/2)=(167+183/2,210+183/2)=(258.5,301.5)
2.屏幕坐标的中心点L(1920/2,1080/2)=(960,540)
3.判断M点的x在图片的左半部分还是右半部分,K.x>512/2为true则K在右半边,对应的屏幕横坐标为L.x+(K.x-512/2),如果为false则K在左半边,对应的屏幕横坐标为L.x-(512/2-K.x)
4.判断M点的y在图片的上半部分还是下半部分,K.y>1024/2为true则K在下半边,对应的屏幕纵坐标为L.y-(K.y-1024/2),如果为false则K在左半边,对应的屏幕横坐标为L.y+(1024/2-K.x)

看代码吧:

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

猜你喜欢

转载自blog.csdn.net/gheartsea/article/details/108442851
今日推荐