【发布时间】:2017-05-22 18:49:17
【问题描述】:
我很难弄清楚如何找到代表 ui 元素区域的正确矩形。我得到了 Ui 元素 RectTransform。我尝试使用函数和 RectTransformUtility 直接使用它,但似乎没有任何问题。 这是代码。
RenderTexture.active = scr;
//adjust rect position
//Rect rect = RectUtils.RectTransformToScreenSpace (rectTransform);
int width = System.Convert.ToInt32 (rect.width);
int height = System.Convert.ToInt32 (rect.height);
// Create a texture the size of the screen, RGB24 format
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
RenderTexture.active = scr;
// Read screen contents into the texture
tex.ReadPixels(rect, 0, 0);
tex.Apply();
RenderTexture.active = null;
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
//todo destroy the texture
Object.Destroy (tex);
// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(path, bytes);
我尝试以不同的方式创建矩形,例如:
方法一:
Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
Rect rect = new Rect(transform.position.x, Screen.height - transform.position.y, size.x, size.y);
rect.x -= (transform.pivot.x * size.x);
rect.y -= ((1.0f - transform.pivot.y) * size.y);
return rect;
方法二:
Vector2 temp = rectT.transform.position;
var startX = temp.x - width/2;
var startY = temp.y - height/2;
var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
tex.ReadPixels (new Rect(startX, startY, width, height), 0, 0);
我使用的是 Unity 5.5 Mac 版本。
当我传递给 ReadPixels new Rect (0, 0, Screen.width, Screen.height) 时,我看到整个 RenderTexture 的定义尺寸为 1920x1080
我想将其用作 UI 元素的烘焙师,因为我遇到了性能问题,并且肯定没有其他解决方案来实现所需的行为。
【问题讨论】: