GUI之绘制2D贴图

来源:互联网 发布:linux切换oracle实例 编辑:程序博客网 时间:2024/05/29 02:32

绘制贴图

在C#编写的脚本中,在屏幕中绘制一张静态贴图,需要使用GUI.DrawTexture()方法,重载方法很多,输入参数可以在写代码时候多看下定义;参数最全的方法的原型为:

public static void DrawTexture(Rect position, Texture image, ScaleMode
scaleMode, bool alphaBlend);
//
// 摘要:
// Draw a texture within a rectangle.
//
// 参数:
// position:
// Rectangle on the screen to draw the texture within.
//
// image:
// Texture to display.
//
// scaleMode:
// How to scale the image when the aspect ratio of it doesn't fit the aspect
// ratio to be drawn within.
//
// alphaBlend:
// Whether to apply alpha blending when drawing the image (enabled by default).
//
// imageAspect:
// Aspect ratio to use for the source image. If 0 (the default), the aspect
// ratio from the image is used. Pass in w/h for the desired aspect ratio. This
// allows the aspect ratio of the source image to be adjusted without changing
// the pixel width and height.

比如:下面的表达式即可绘制贴图,注意C#中使用new Rect(…),而JavaScript中直接使用Rect(…),只是因为C#中的原型要求Rect position = new Rect(…)这样的表达式。

GUI.DrawTexture(new Rect(100, 20, 50, 50), texSingle, ScaleMode.StretchToFill, true, 0);

注意:C#中:className obj = new className();// obj是引用,本质是地址,不使用指针 。C++中: className *obj = new className();// 这里使用的是指针

加载资源

1.资源必须放在Resources 文件夹中;
2.加载资源为Resources.Load()Resources.LoadAll() 方法,参数均为资源文件夹的完整路径,前者返回读取的资源对象,后者返回的是资源对象的数组。

具体用法参看下面的代码清单:

using UnityEngine;using System.Collections;public class TextureTest : MonoBehaviour {    public float startX, startY;// 设置为公有,可以在U3D的Inspector中进行设置数值    public Texture2D texSingle;// 一张贴图    public Object[] texAll; // 一组贴图对象    // Update is called once per frame    void OnGUI () {        /* ------------------ 加载贴图 ---------------------------- */         if (GUI.Button(new Rect(startX, startY, 100, 20), "加载一张帖图")){            if (texSingle == null){                // 加载单个贴图                texSingle = (Texture2D)Resources.Load("single/0");            }        }        if (GUI.Button(new Rect(startX, startY + 60, 100, 20), "加载一组贴图")){            // 加载一组贴图,textures文件夹中的所有贴图            texAll = Resources.LoadAll("textures");// public static Object[] Load(string path);        }        /* ------------------ 设置布局、绘制贴图 ------------------ */         // 默认垂直布局        // 第一行的水平线性布局        GUILayout.BeginHorizontal();        if (texSingle != null){            // 绘制贴图            GUI.DrawTexture(new Rect(startX + 100, startY, 50, 50), texSingle, ScaleMode.StretchToFill, true, 0);        }        GUILayout.EndHorizontal();        // 第二行水平线性布局        GUILayout.BeginHorizontal();        if (texAll != null) {            for (int i = 0; i < texAll.Length; ++i) {                Texture2D tmp = (Texture2D)texAll[i];                GUI.DrawTexture(new Rect(startX + 50 * i + 100, startY + 60, 50, 50), tmp,                    ScaleMode.StretchToFill, true, 0);            }         }        GUILayout.EndHorizontal();    }}

0 0
原创粉丝点击