Unity 6.3
0 онлайн 13 гостей 3 в системе
Вход

Texture2D.ReadPixels

Declaration

public void ReadPixels(Rect source, int destX, int destY, bool recalculateMipMaps = true);

Параметры

Параметр Описание
источник Область рендеринга, из которой будет выполняться чтение.
destX Позиция x в текстуре, в которую будут записаны пиксели.
destY Позиция y в текстуре, в которую будут записаны пиксели.
recalculateMipMaps Когда значением является true, Unity автоматически пересчитывает mipmap для текстуры после записи данных пикселей. В противном случае Unity не делает этого автоматически.

Описание

Читает пиксели из текущего объекта рендеринга и записывает их в текстуру.

Этот метод копирует прямоугольную область цветов пикселей из текущего активного объекта рендеринга на GPU (например, экран, RenderTexture, или GraphicsTexture) и записывает их в текстуру на CPU в позиции (destX, destY). Texture.isReadable должны быть true, и вы должны вызвать Apply после ReadPixels, чтобы загрузить измененные пиксели на GPU.

Нижний левый угол (0, 0).

ReadPixels обычно медленно, потому что метод ожидает, пока GPU завершит всю предыдущую работу. Чтобы скопировать текстуру быстрее, используйте один из следующих методов:

Цель рендеринга и текстура должны использовать один и тот же формат, и этот формат должен поддерживаться на устройстве как для рендеринга, так и для семплинга.

Вы можете автоматически обновлять mipmap при вызове Apply вместо установки recalculateMipMaps на true.

В следующем примере кода показано, как использовать ReadPixels в Built-in Render Pipeline. В Scriptable Render Pipelines, таких как Universal Render Pipeline (URP), Camera.onPostRender недоступны, но вы можете использовать RenderPipelineManager.endCameraRendering аналогичным образом.

using UnityEngine;

public class ReadPixelsExample : MonoBehaviour { // Set Renderer to a GameObject that has a Renderer component and a material that displays a texture public Renderer screenGrabRenderer;

private Texture2D destinationTexture; private bool isPerformingScreenGrab;

void Start() { // Create a new Texture2D with the width and height of the screen, and cache it for reuse destinationTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

// Make screenGrabRenderer display the texture. screenGrabRenderer.material.mainTexture = destinationTexture;

// Add the onPostRender callback Camera.onPostRender += OnPostRenderCallback; }

void Update() { // When the user presses the Space key, perform the screen grab operation if (Input.GetKeyDown(KeyCode.Space)) { isPerformingScreenGrab = true; } }

void OnPostRenderCallback(Camera cam) { if (isPerformingScreenGrab) { // Check whether the Camera that just finished rendering is the one you want to take a screen grab from if (cam == Camera.main) { // Define the parameters for the ReadPixels operation Rect regionToReadFrom = new Rect(0, 0, Screen.width, Screen.height); int xPosToWriteTo = 0; int yPosToWriteTo = 0; bool updateMipMapsAutomatically = false;

// Copy the pixels from the Camera's render target to the texture destinationTexture.ReadPixels(regionToReadFrom, xPosToWriteTo, yPosToWriteTo, updateMipMapsAutomatically);

// Upload texture data to the GPU, so the GPU renders the updated texture // Note: This method is costly, and you should call it only when you need to // If you do not intend to render the updated texture, there is no need to call this method at this point destinationTexture.Apply();

// Reset the isPerformingScreenGrab state isPerformingScreenGrab = false; } } }

// Remove the onPostRender callback void OnDestroy() { Camera.onPostRender -= OnPostRenderCallback; } }

Дополнительные ресурсы: ,ImageConversion.EncodeToPNG,.