在Unity 中要通过代码将一张贴图切割成多张小图,可以使用以下方法:
/// <summary>
/// 把一张图片切割成多张使用
/// </summary>
/// <param name="texture">原图</param>
/// <param name="rows">切割的行数</param>
/// <param name="columns">切割的列数</param>
/// <returns></returns>
public List<Texture2D> CutPic(Texture2D texture,int rows,int columns)
{
List<Texture2D> texs = new List<Texture2D>();
int width = texture.width / columns;
int height = texture.height / rows;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
int x = col * width;
int y = row * height;
Rect rect = new Rect(x, y, width, height);
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
//Sprite sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
Color[] pixels = texture.GetPixels(x, y, width, height);
tex.SetPixels(pixels);
tex.Apply();
texs.Add(tex);
}
}
return texs;
}
注意:要想成功实现切割,要保证图片是可读的。
使用上面方法我把场景中RawImage里面的贴图切成4块,
List<Texture2D> textures = CutPic((Texture2D)bigImg.texture, 2, 2);
然后再把切出的图分别给到4个新的RawImage,效果如下图。
完成得不错!