如何从单文件精灵表中获取单个Sprite的Texture2D?
从精灵表提取单帧Texture2D的实现思路
方法1:手动裁剪纹理(通用方案)
直接操作原纹理的像素数据,裁剪出目标单帧区域并生成新的Texture2D,适配绝大多数游戏引擎:
- 先计算单帧尺寸:
单帧宽 = 精灵表宽度 / 横向帧数(Hframes),单帧高 = 精灵表高度 / 纵向帧数(Vframes) - 确定目标帧的起始坐标:比如要取第
col列第row行的帧,起始X为col * 单帧宽,起始Y为row * 单帧高(注意部分引擎纹理坐标系是Y轴向下,可能需要用总纵向帧数-1-row来计算Y坐标) - 创建对应尺寸的新Texture2D,读取原纹理对应区域的像素数据写入新纹理,最后应用修改
以Unity引擎为例,示例代码如下:
public Texture2D ExtractSingleFrame(Texture2D spritesheet, int hFrames, int vFrames, int targetCol, int targetRow) { int frameWidth = spritesheet.width / hFrames; int frameHeight = spritesheet.height / vFrames; // 适配Unity纹理Y轴向下的坐标系 int startX = targetCol * frameWidth; int startY = (vFrames - 1 - targetRow) * frameHeight; Texture2D singleFrame = new Texture2D(frameWidth, frameHeight); Color[] pixels = spritesheet.GetPixels(startX, startY, frameWidth, frameHeight); singleFrame.SetPixels(pixels); singleFrame.Apply(); return singleFrame; }
方法2:利用引擎内置图集工具(推荐)
你提到的AtlasTexture如果是Godot引擎的API,完全适配你的场景。这种方式不需要复制像素,只是对原纹理的区域引用,性能更优:
public Texture2D GetFrameFromAtlas(Texture2D spritesheet, int hFrames, int vFrames, int col, int row) { int frameWidth = (int)spritesheet.GetWidth() / hFrames; int frameHeight = (int)spritesheet.GetHeight() / vFrames; Rect2 frameRect = new Rect2(col * frameWidth, row * frameHeight, frameWidth, frameHeight); AtlasTexture atlasTexture = new AtlasTexture(); atlasTexture.Atlas = spritesheet; atlasTexture.Region = frameRect; return atlasTexture; }
针对你现有Sprite2D代码的补充说明
你当前的代码只是给Sprite2D划分了帧格范围,但如果要获取独立的Texture2D对象,不能直接从Sprite2D中提取,得用上面两种方法。如果只是想让Sprite2D显示单帧,其实可以直接开启区域裁剪:
// 以Godot的Sprite2D为例 _dummySprite.RegionEnabled = true; int frameWidth = (int)_dummySprite.Texture.GetWidth() / _dummySprite.Hframes; int frameHeight = (int)_dummySprite.Texture.GetHeight() / _dummySprite.Vframes; // 替换targetCol和targetRow为你要显示的帧坐标 _dummySprite.RegionRect = new Rect2(targetCol * frameWidth, targetRow * frameHeight, frameWidth, frameHeight);
这种方式只是控制显示区域,不会生成新的Texture2D对象。
内容的提问来源于stack exchange,提问作者Mykyta
相关产品推荐
相关产品推荐

