How to ReadPixels from square area right in the middle of the screen?
I need to capture pixels from square area in the middle of the screen, its' width equals Screen.width, so its' height equals the same. Afterwards I set the captured pixels as a sprite to existing Image, so as a result i should get the same square-shaped Image in the middle of the screen. But what I get looks like rect half of which is part of captured area and another half is just plain grey color.
RectTransform rt = parentSpinner.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(tex.width, tex.height);
parentSpinner.GetComponent<Image> ().sprite = Sprite.Create (tex, new Rect (0, 0, tex.width, tex.height), new Vector2 (0, 0));
Answer by Jairolaya12x · Mar 30, 2018 at 06:47 AM
Hey bro,
Replace the renderer by a component image, is the same way (I used the renderer for testing)
I wanted make the same that you, and this code works for me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TakeScreenShot : MonoBehaviour {
private bool takeScrenShoot;
public RectTransform rectTransformToSH;
public Renderer renderer;
public Canvas canvas;
Rect rect;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(CaptureScreen());
}
}
IEnumerator CaptureScreen()
{
yield return new WaitForEndOfFrame();
//Rect rect = new Rect(new Vector2(rt.position.x, rt.position.y), rt.sizeDelta);
rect = new Rect(rectTransformToSH.position - new Vector3(rectTransformToSH.sizeDelta.x * 0.5f * canvas.scaleFactor, rectTransformToSH.sizeDelta.y * 0.5f * canvas.scaleFactor), rectTransformToSH.sizeDelta * canvas.scaleFactor);
Debug.LogError("rect is : " + rect);
Texture2D tex = new Texture2D((int)rect.width, (int)rect.height);
tex.ReadPixels(rect, 0, 0, true);
tex.Apply();
renderer.material.mainTexture = tex;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612121834im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Texture2D.ReadPixels doesn't capture image effects. 1 Answer
ReadPixels returns empty texture 0 Answers
Rendering Camera to PNG produces completely grey image. 1 Answer
Texture2D ReadPixels for specific Display 0 Answers
ScreenCapture.CaptureScreenshotAsTexture() is making a milky white tinted screenshot. 1 Answer