用unity保存相机渲染结果为图片

转载请注明来源

起因
mobile做特效费资源,是不是可以用unity做好特效再保存为图片动画使用呢?

思路
使用相机,rendertexture,io来保存特效图片

建议
开发者自己实现观察者再每一次控制动画的变量变换后从rendertexture创建一个texture2D,保存成列表
最后一起保存到文件,再根据需要调整或者删除这些得到的图片

截图

EFX0.png
image.png
image.png

代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SaveRenderTexture : MonoBehaviour
{

public RenderTexture target;

int index = 0;

private void Start()
{
    GameObject.Find("SaveBtn").GetComponent<Button>().onClick.AddListener(()=> {
        OnUserSave();
    });
}

public void OnUserSave()
{
    var prePath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/"));
    string path = prePath + string.Format("/SaveFX/EFX{0}.png",index);
    Save(path, CreateFrom(target));
    index++;
}

public void Save(string path, Texture2D texture2D)
{
    Debug.Log("Save Path:" + path);
    var bytes = texture2D.EncodeToPNG();
    //var bytes = texture2D.EncodeToJPG();
    System.IO.File.WriteAllBytes(path, bytes);
}

public Texture2D CreateFrom(RenderTexture renderTexture)
{
    Texture2D texture2D = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
    var previous = RenderTexture.active;
    RenderTexture.active = renderTexture;

    texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);

    RenderTexture.active = previous;

    texture2D.Apply();

    return texture2D;
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 粽子今年四岁,而我刚开始正面管教的学习。白天我去工作,粽子由老人接送幼儿园,白天的时间他在幼儿园度过。我和他相处的...
    我是写作小白阅读 310评论 3 1
  • 刚到一个新城市,马上就收到短信“***欢迎您”,顿时感受到这个城市的热情。然后,一连串的拇指“点击”,就让初来乍到...
    效率源科技阅读 1,148评论 1 0
  • 枫叶红了 那是一颗再也捂不住的朱砂痣 它怕思念累了也会冬眠 不得已羞了脸颊 告诉你,我在秋里 等风,也等你 树叶落...
    OneStep壹步阅读 394评论 0 0
  • 作为一个纯正的东北女汉子,在江南的夏天里,热的有些不知所措。于是,备齐材料,给自己煮上一碗银耳莲子羹,放在冰箱里,...
    逄小胖阅读 274评论 0 0
  • 陪伴 公交站等着你下班,狭窄出租屋里飘香的晚饭,你走在我左边渐成习惯,有你陪伴做梦也是甜 你把玫瑰换成了三餐,浪漫...
    缘枚阅读 241评论 2 3