Unity Texture2D.ReadPixels在Android上的读取方式不同



我们正试图捕捉屏幕的一个区域供玩家共享。在编辑器中,捕捉效果很好,它捕捉到了确切的区域。然而,在安卓系统上,该区域似乎因设备本身而异。在一台设备上,它捕捉到的区域要大得多,而在另一台设备中,它捕捉的区域要小得多。但是,最终的图像大小总是相同的。这让我觉得在拍摄屏幕时缩放或平移是不正确的。然而,从视觉上看,一切都是正确的。我正在使用Unity 2020.1.10

我将要截图的面板分配给recT。

public class ElementScreenshot : MonoBehaviour
{
public RectTransform rectT; // Assign the UI element which you wanna capture
//public Image img;
int width; // width of the object to capture
int height; // height of the object to capture
// Use this for initialization
void Start()
{
width = System.Convert.ToInt32(rectT.rect.width);
height = System.Convert.ToInt32(rectT.rect.height);
}
public IEnumerator takeScreenShot(string filePath)
{
yield return new WaitForEndOfFrame(); // it must be a coroutine 
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);
tex.Apply();
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Destroy(tex);

File.WriteAllBytes(filePath, bytes);
}
public string Capture()
{
var filePath = Path.Combine(Application.temporaryCachePath, "shared_image.png");
StartCoroutine(takeScreenShot(filePath)); // screenshot of a particular UI Element.
return filePath;
}
}

问题在于使用rect。以下更改修复了此问题。

public IEnumerator takeScreenShot(string filePath)
{
yield return new WaitForEndOfFrame(); // it must be a coroutine 
var r = RectTransformToScreenSpace(rectT);
var tex = new Texture2D((int)r.width, (int)r.height, TextureFormat.RGB24, false);

tex.ReadPixels(r, 0, 0);
tex.Apply();            
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Destroy(tex);

File.WriteAllBytes(filePath, bytes);
}
public static Rect RectTransformToScreenSpace(RectTransform transform)
{
Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
return new Rect((Vector2)transform.position - (size * 0.5f), size);
}

最新更新