// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit
{
///
/// A collection of helper functions for Texture2D
///
public static class Texture2DExtensions
{
///
/// Fills the pixels. You will need to call Apply on the texture in order for changes to take place.
///
/// The Texture2D.
/// The row to start filling at.
/// The column to start filling at.
/// The width to fill.
/// The height to fill.
/// Color of the fill.
/// This function considers row 0 to be left and col 0 to be top.
public static void FillPixels(this Texture2D texture2D, int row, int col, int width, int height, Color fillColor)
{
if (col + width > texture2D.width || row + height > texture2D.height)
{
throw new IndexOutOfRangeException();
}
Color32 toColor = fillColor; // Implicit cast
Color32[] colors = new Color32[width * height];
for (int i = 0; i < colors.Length; i++)
{
colors[i] = toColor;
}
texture2D.SetPixels32(col, (texture2D.height - row) - height, width, height, colors);
}
///
/// Fills the texture with a single color.
///
/// The Texture2D.
/// Color of the fill.
public static void FillPixels(this Texture2D texture2D, Color fillColor)
{
texture2D.FillPixels(0, 0, texture2D.width, texture2D.height, fillColor);
}
///
/// Captures a region of the screen and returns it as a texture.
///
/// x position of the screen to capture from (bottom-left)
/// y position of the screen to capture from (bottom-left)
/// width of the screen area to capture
/// height of the screen area to capture
/// A Texture2D containing pixels from the region of the screen specified
/// You should call this in OnPostRender.
public static Texture2D CaptureScreenRegion(int x, int y, int width, int height)
{
Texture2D tex = new Texture2D(width, height);
tex.ReadPixels(new Rect(x, y, Screen.width, Screen.height), 0, 0);
tex.Apply();
return tex;
}
///
/// Creates a texture from a defined region.
///
/// The Texture2D.
/// x position of this texture to get the texture from
/// y position of this texture to get the texture from
/// width of the region to capture
/// height of the region to capture
public static Texture2D CreateTextureFromRegion(this Texture2D texture2D, int x, int y, int width, int height)
{
Color[] pixels = texture2D.GetPixels(x, y, width, height);
Texture2D destTex = new Texture2D(width, height);
destTex.SetPixels(pixels);
destTex.Apply();
return destTex;
}
}
}