我們平時在做項目時,經常遇到按鈕的點擊而且還要區分懸浮,點擊,禁用的狀態,美術要針對一張圖片做多個狀態圖片,資源圖片的數量也就增大了,那么打出的包的大小也就跟着上去了,所以我們可以針對原始圖片進行Shader處理,得到我們想要的效果!
實現原理:Unity3d中所有的渲染都是基於Shader的,而Shader綁定在Material上,打開一個NGUI例子中自帶的Material,得到其使用Shader的文件NGUI中大部分材質都使用的Unlit/Transparent Colored(PS:雖然在Unlit下,但並不是Unity3d內置的,而是NGUI擴展的)找到其片段着色器,在Unity中的路徑:
代碼如下:
fixed4 frag (v2f i) : COLOR { fixed4 col = tex2D(_MainTex, i.texcoord) * i.color; return col; }
我們對其做下修改:
fixed4 frag (v2f i) : COLOR { fixed4 col; if (i.color.r < 0.001) { col = tex2D(_MainTex, i.texcoord); float grey = dot(col.rgb, float3(0.299, 0.587, 0.114)); col.rgb = float3(grey, grey, grey); } else { col = tex2D(_MainTex, i.texcoord) * i.color; } return col; }
至於為什么是(0.299,0.587,0.114)前往 http://blog.csdn.net/zyl910/article/details/753814
PS:(0.299,0.587,0.114)為灰度公式的參數。
那么接下來就要驗證這一結論了,建立測試工程,導入NGUI插件:
我們添加測試規資源,Unity3D支持的圖形文件格式有 PSD, TIFF, JPG, TGA, PNG, GIF, BMP, IFF, PICT。但是我們要測試的對象主要是Texture,Sprite,但是在游戲中圖片出現的格式也就這么兩種。
Shder修改過了,我怎么才能實現灰度效果呢?往下看。。。。
只需要這樣就OK了。那么接下來有人會疑問了,我在代碼里該怎么做呢,實際的邏輯控制怎么寫?
那么我們就在代碼里測試一下:
using UnityEngine;
using System.Collections;
public class TestFadeGray : MonoBehaviour
{
UITexture texture;
// Use this for initialization
void Start ()
{
texture = this.GetComponent<UITexture>();
Debug.Log(texture.color);
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
FadeGray(texture);
}
}
void FadeGray(UITexture texture)
{
Debug.Log("置灰操作");
texture.color = new Color(0, 1, 1, 1);
Debug.Log(texture.color);
}
}
運行后,輸出Texture的RGBA的值:
點擊之后,效果如下:
OK了吧!如果有疑問,可以聯系我哦!
工程源碼:http://pan.baidu.com/s/1eQ375Ai
