需求:项目里需要对游戏截图进行抠图和裁剪。
/// <summary>
/// 抠图
/// </summary>
/// <param name="texture2D"></param>
/// <returns></returns>
private Texture2D GetTexture2D(Texture2D texture2D,int CaptureWidth,int CaptureHeight)
{
var camera = Camera.main;
if (camera == null) return null;
RenderTexture target = RenderTexture.GetTemporary(CaptureWidth, CaptureHeight, 24, RenderTextureFormat.DefaultHDR);
CameraClearFlags preClearFlags = camera.clearFlags;
RenderTexture preTargetTexture = camera.targetTexture;
RenderTexture preActiveTexture = RenderTexture.active;
Color preBackgroundColor = camera.backgroundColor;
camera.clearFlags = CameraClearFlags.Color;
camera.targetTexture = target;
RenderTexture.active = target;
camera.backgroundColor = Color.black;
camera.Render();
Texture2D captureBlack = new Texture2D(CaptureWidth, CaptureHeight, TextureFormat.RGBAFloat, false);
captureBlack.ReadPixels(new Rect(0f, 0f, CaptureWidth, CaptureHeight), 0, 0, false);
captureBlack.Apply();
camera.backgroundColor = Color.white;
camera.Render();
Texture2D captureWhite = new Texture2D(CaptureWidth, CaptureHeight, TextureFormat.RGBAFloat, false);
captureWhite.ReadPixels(new Rect(0f, 0f, CaptureWidth, CaptureHeight), 0, 0, false);
captureWhite.Apply();
texture2D = new Texture2D(CaptureWidth, CaptureHeight, TextureFormat.RGBAFloat, false);
for (int x = 0; x < CaptureWidth; ++x)
{
for (int y = 0; y < CaptureHeight; ++y)
{
Color lColorWhenBlack = captureBlack.GetPixel(x, y);
Color lColorWhenWhite = captureWhite.GetPixel(x, y);
Color lColorCombined = (lColorWhenBlack + lColorWhenWhite) * 0.5f;
float alphaR = 1 + lColorWhenBlack.r - lColorWhenWhite.r;
float alphaG = 1 + lColorWhenBlack.g - lColorWhenWhite.g;
float alphaB = 1 + lColorWhenBlack.b - lColorWhenWhite.b;
float alpha = (alphaR + alphaG + alphaB) / 3f;
Color color = new Color(lColorCombined.r, lColorCombined.g, lColorCombined.b, alpha);
texture2D.SetPixel(x, y, color);
}
}
texture2D.Apply();
RenderTexture.active = preActiveTexture;
camera.targetTexture = preTargetTexture;
camera.backgroundColor = preBackgroundColor;
camera.clearFlags = preClearFlags;
return texture2D;
}
/// <summary>
/// 裁剪或者拷贝图片,图片的原点在左下角
/// </summary>
/// <param name="原图"></param>
/// <param name="x,y表示从原图的什么位置开始裁剪,w,h表示裁剪的宽高"></param>
/// <param name="x,y表示拷贝到新的图片中的什么位置,w,h新的图片的宽高"></param>
/// <returns></returns>
Texture2D CutOrCopyTexture(Texture2D source, RectInt cutScope, RectInt targetScope)
{
Texture2D target = new Texture2D(targetScope.width, targetScope.height, source.format, false);
Graphics.CopyTexture(source, 0, 0, cutScope.x, cutScope.y, cutScope.width, cutScope.height, target, 0, 0, targetScope.x, targetScope.y);
return target;
}