使用一个image 来确定截图的位置
效果图:
左边是截图出来的 ,右边是要截取的位置
public GameObject iamge; //需要截取的位置
//public RawImage image2; //截取后贴到rawimage上
public Camera uic; //相机
public Vector2 off; //在外部调节截图区域
//---------------------------
public IEnumerator Pictures ()
{
yield return new WaitForSeconds(3);
yield return new WaitForEndOfFrame();
//得到截图区域
var a = iamge.GetComponent<RectTransform>();
//初始化一个Texture2D
Texture2D screenShot = new Texture2D((int)(a.rect.width*(Screen.width /1920.0f)),
(int)(a.rect.height*(Screen.width /1920.0f)),
TextureFormat.RGB24, true);
float x = a.localPosition.x + (Screen.width - a.rect.width) / 2;
float y = a.localPosition.y + (Screen.height - a.rect.height) / 2;
print(Screen.width);
print(Screen.height);
//转换坐标
var temp = RectTransformUtility.WorldToScreenPoint(uic, a.position);
//
Rect position = new Rect(temp.x - a.rect.width*Screen.width /1920.0f / 2 + off.x,
temp.y - a.rect.width*Screen.width /1920.0f / 2 + off.y,
a.rect.width*Screen.width /1920.0f,
a.rect.height*Screen.width /1920.0f);
Debug.Log(temp.x + "eee" + temp.y + "ee" + a.rect.width + "ee" + a.rect.height);
screenShot.ReadPixels(position, 0, 0, true);//按照设定区域读取像素;注意是以左下角为原点读取
screenShot.Apply();
//image2.texture = screenShot;
byte[] bytes = screenShot.EncodeToPNG();
b= Convert.ToBase64String(bytes);
}
Image 截取的位置 //我取得是蓝色背景
Image2 截取的图片传到RawImage上
Uic 相机
Off 用来调节误差
新手时期写的东西比较烂后期会对内容进行调整 /2022.6.22