统一拍照c#

时间:2017-04-07 10:10:09

标签: unity3d screenshot photo

我正在尝试构建一个程序来拍摄你的照片并将其放置在不同的背景中,就像纪念碑一样。到目前为止,当我使用此代码启动项目时,我能够打开相机

 webcamTexture = new WebCamTexture();
 rawImage.texture = webcamTexture;
 rawImage.material.mainTexture = webcamTexture;
 webcamTexture.Play();
 Texture2D PhotoTaken = new Texture2D (webcamTexture.width, webcamTexture.height);
 PhotoTaken.SetPixels (webcamTexture.GetPixels ());
 PhotoTaken.Apply ();

但是,我无法截取屏幕截图或照片,因为它总是全黑。我尝试了不同的代码,但没有任何工作。有人可以帮忙吗?感谢

编辑

经过一些尝试,这是我的代码:

WebCamTexture webcamTexture;
public RawImage rawImage;


void Start () {
    webcamTexture = new WebCamTexture();
    rawImage.texture = webcamTexture;
    rawImage.material.mainTexture = webcamTexture;
    webcamTexture.Play();

    RenderTexture texture= new RenderTexture(webcamTexture.width, webcamTexture.height,0); 
    Graphics.Blit(webcamTexture, texture);

    Button btn = yourButton.GetComponent<Button>();
    btn.onClick.AddListener(OnClick);

}

public IEnumerator Coroutine(){

    yield return new WaitForEndOfFrame ();
}

public void OnClick() {

    var width = 767;
    var height = 575;

    Texture2D texture = new Texture2D(width, height);
    texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
    texture.Apply();

    // Encode texture into PNG
    var bytes = texture.EncodeToPNG();
    //Destroy(texture);


    File.WriteAllBytes (Application.dataPath + "/../SavedScreen.png", bytes);

    }

并使用下一个代码截取屏幕截图,但它会拍摄整个事物的照片,而不仅仅是屏幕上的一小部分。

void Start()
{
    // Set the playback framerate!
    // (real time doesn't influence time anymore)
    Time.captureFramerate = frameRate;

    // Find a folder that doesn't exist yet by appending numbers!
    realFolder = folder;
    int count = 1;
    while (System.IO.Directory.Exists(realFolder))
    {
        realFolder = folder + count;
        count++;
    }
    // Create the folder
    System.IO.Directory.CreateDirectory(realFolder);
}

void Update()
{
    // name is "realFolder/shot 0005.png"
    var name = string.Format("{0}/shot {1:D04}.png", realFolder, Time.frameCount);

    // Capture the screenshot
    Application.CaptureScreenshot(name, sizeMultiplier);
}

}

1 个答案:

答案 0 :(得分:2)

您可以在Unity

中截取此类屏幕截图
    Application.CaptureScreenshot("Screenshot.png");

Reference

编辑1
要在屏幕的特定部分截取屏幕截图,请使用以下脚本:

 var width = 400;
 var height = 300;
 var startX = 200;
 var startY = 100;
 var tex = new Texture2D (width, height, TextureFormat.RGB24, false);

 tex.ReadPixels (Rect(startX, startY, width, height), 0, 0);
 tex.Apply ();

 // Encode texture into PNG
 var bytes = tex.EncodeToPNG();
 Destroy(tex);

 File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);

Reference