美文网首页
Texture2D与Sprite类

Texture2D与Sprite类

作者: 迷途小路 | 来源:发表于2019-04-15 15:32 被阅读0次

这一节看一下图片资源的应用,我们平时所用的图片格式有.png,.jpg等,在unity中都会转换为texture格式,如


image.png

如果我们要把它放在Image控件上,必须转换为Sprite格式,如:


image.png
可以看到,图片"组4"下面多出了一个同名的资源。图中mip Maps选中表示会根据摄像机远近不同而生成对应的八个贴图,适用于会根据场景来显示不同清晰度的图片。

一个texture2D格式不仅可以生成一个Sprite,还可以生成多个,如:


image.png

在Sprite Mode中选择 Multiple,可以在Sprite Editor中划出多个区域,点击Apply后可在图片“组4”下看到多个Sprite,这个时候会发现只能拖动"组4_0"这样的Sprite进入Image中了,Texture“组4”就无法拖进Image了。当然只有一张Sprite的时候可以,因为它默认会选中内部唯一的那个Sprite。


image.png

接下来我们通过一个小demo来加深认识,先获取计算机文件夹里的一张.png图片,生成一个Texture2D的对象,用它去加载这个图片,前面说了Texture2D不能赋给Image,因此我们还要用这个texture2D创建一个Sprite的对象

public Image image;
    // Use this for initialization 
    void Start () {
        byte[] byteData = System.IO.File.ReadAllBytes ("C:/Users/0001/Pictures/Camera Roll/20190123163748.png");
        Texture2D texture = new Texture2D (1, 1, UnityEngine.TextureFormat.RGB565, false);
        texture.LoadImage (byteData);
        texture.Apply ();
        Sprite sprite = Sprite.Create (texture, new Rect (0, 0, texture.width, texture.height), new Vector2 (0.5f, 0.5f));

        image.overrideSprite = sprite;
    }

Texture2D的构造方法里前2项是宽高,3是texture格式,4是是否是mipMap图片。Sprite.Create方法传入这个texture2D对象、一个Rect类对象和一个重心位置即可。详情可查API文档。试验一下,在控件Image中确实加载了这个图片。


image.png

不足之处,多谢指正。

相关文章

网友评论

      本文标题:Texture2D与Sprite类

      本文链接:https://www.haomeiwen.com/subject/hwpuwqtx.html