Unity屏幕截图保存(适应分辨率变化)

Unity屏幕截图保存

截取任意分辨率下Canvas内任意位置任意大小的recttransform的内容。

代码

    public IEnumerator SavePic(Canvas canvas, RectTransform target, string savePath)
    {
        yield return new WaitForEndOfFrame();
        //Canvas的sizeDelta
        Vector3 canvasSize = canvas.GetComponent<RectTransform>().sizeDelta;
        //截取目标的左下角
        Vector2 origin = new Vector2((target.localPosition.x + (canvasSize.x - target.rect.width) / 2f) * Screen.width / canvasSize.x,
            (target.localPosition.y + (canvasSize.y - target.rect.height) / 2f) * Screen.height / canvasSize.y);
        //截取目标的大小
        Vector2 size = new Vector2(target.rect.width * Screen.width / canvasSize.x, target.rect.height * Screen.height / canvasSize.y);

        //截取
        Texture2D screenShot = new Texture2D((int) size.x, (int) size.y, TextureFormat.RGB24, true);
        Rect position = new Rect(origin.x, origin.y, size.x, size.y);
        screenShot.ReadPixels(position, 0, 0, true); //按照设定区域读取像素;注意是以左下角为原点读取
        screenShot.Apply();

        //保存
        string filePath = savePath + ".jpg";
        byte[] byt = screenShot.EncodeToPNG();
        File.WriteAllBytes(filePath, byt);
        System.Diagnostics.Process.Start(filePath);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值