Unity功能记录(六)------ UGUI获取UI在Canvas下的坐标/根据UI位置获取屏幕图片/二维码识别

版权声明:个人原创,转载请注明出处 https://blog.csdn.net/dengshunhao/article/details/81902352

前些日子在做二维码扫描,使用的是ZXing插件,不过好像新版的不支持IOS,IOS找到一个可以用的demo,不过是原生的,后面有空再整理一个可供unity使用的出来,在此把可用的Android/iOS二维码识别链接整理如下:

1.二维码识别

IOS(使用ZBar):

   项目demo下载:https://github.com/jaybinhe/JB_ZBarSDK_Demo

   文章:https://blog.csdn.net/He_jiabin/article/details/47786031

Android(使用ZBar):

   demo下载:https://github.com/micjahn/ZXing.Net

2. UGUI获取UI在Canvas下的坐标

以下是获取UI左下角位置的坐标:


public Vector2 leftPos;
public RectTransform QRCodeBorder;

leftPos = Camera.main.WorldToScreenPoint(QRCodeBorder.transform.position);
leftPos.x -= QRCodeBorder.rect.width / 2;
leftPos.y -= QRCodeBorder.rect.height / 2;

同理也可以获取其他三个角的坐标

3.根据UI位置获取屏幕图片

首先要获取UI左下角位置与宽高,并根据宽高偏移量计算识别区域大小

    //位置参数
    public int width;
    public int height;
    //二维码识别,要比图片框住的大一些,因此可以加一些偏移量
    public int WOffect = 10; 
    public int HOffect = 10;
    public Vector2 leftPos;

    void Start () {
        if (QRCodeBorder.rect.width + WOffect < Screen.width)
        {
            width = (int)QRCodeBorder.rect.width + WOffect;
        }
        else
        {
            width = (int)QRCodeBorder.rect.width;
        }
        if(QRCodeBorder.rect.height + HOffect < Screen.height)
        {
            height = (int)QRCodeBorder.rect.height + HOffect;
        }
        else
        {
            height = (int)QRCodeBorder.rect.height;
        }
        leftPos = Camera.main.WorldToScreenPoint(QRCodeBorder.transform.position);
        leftPos.x -= QRCodeBorder.rect.width / 2;
        leftPos.y -= QRCodeBorder.rect.height / 2;

    }

截取屏幕图片:

   void getScreenTexture(Camera c)
    {
        Rect r = new Rect((int)leftPos.x, (int)leftPos.y, width, height);
        RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 0);
        c.targetTexture = rt;
        c.Render();
        RenderTexture.active = rt;
        CamTexture = new Texture2D(width,height, TextureFormat.RGB24, false);
        CamTexture.ReadPixels(r, 0,0);
        CamTexture.Apply();
        c.targetTexture = null;
        RenderTexture.active = null;
        Destroy(rt);
    }

猜你喜欢

转载自blog.csdn.net/dengshunhao/article/details/81902352