最近项目中需要通过图片中子图的左上角与右下角坐标实现子图的截取。
原图 子图
- 主要代码:public Color[] GetPixels(int x, int y, int blockWidth, int blockHeight);
注意:x和y就是子图的左下角坐标,blockWidth和blockHeight分别是矩形的宽和高;
该函数获取像素是以原图左下方为(0,0)点,所以
子图的左下角坐标在该坐标系下为(子图左上角横坐标,
原图的高减去子图右下角纵坐标
)
- 具体代码:
void CaptureScreenShot(int x1, int y1, int x2, int y2, Sprite source = null)
{
if (source != null)
{
ImageManager._instance. texture = new Texture2D(x2 - x1, y2 - y1);
var color = source.texture.GetPixels(x1, source.texture.height-y2, x2 - x1, y2 - y1);
ImageManager._instance. texture.SetPixels(color);
ImageManager._instance. texture.Apply();
}
}
- 参数 x1,y1为子图左上角坐标, x2,y2为子图右下角坐标,source为原图。
- 代码截图如下: