Unity3d中設置UISprite圖片灰顯方法

作Unity開發過程當中,有需求讓未開啓的功能模塊的入口灰色顯示。由於沒有濾鏡的概念,因此沒flash那麼方便。解決思路仍是Shader,之前按網上其餘帖子的方法,一直沒有成功實現過。這兩天比較閒一點,專門研究了下,總算成功了。css

 

NGUI裏已經有Unlit - Transparent Colored.shader。通常打Atlas的時候默認就是這個。以下圖。html

 

fixed4 frag (v2f IN) : COLOR
{
    return tex2D(_MainTex, IN.texcoord) * IN.color;
}
ENDCG

上面就是Transparent Colored.shader內的核心顏色渲染代碼,可見是沒有灰色轉換的功能的。咱們這裏須要使用另外個shader,也是NGUI自帶的:Unlit - Transparent Colored Gray.shader,它的核心代碼以下:spa

fixed4 frag (v2f IN) : COLOR  
{  
	fixed4 col;  
	if (IN.color.r < 0.001)  
	{  
		col = tex2D(_MainTex, IN.texcoord);  
		float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));  
		col.rgb = float3(grey, grey, grey);  
	}  
	else  
	{  
		col = tex2D(_MainTex, IN.texcoord) * IN.color;  
	}  
	return col;  
}

當顏色值的r值爲0的時候,就灰色顯示。code

圖集打好後,咱們看看效果:htm

 

咱們將r設置爲0,可是圖片仍是沒有成灰色,這是爲什麼呢?後來根據http://bbs.9ria.com/thread-431562-1-1.html的啓示,找到NGUI,UIDrawCall.cs類,發現若是是Scroll下,NGUI會更改默認shader,咱們是Unlit - Transparent Colored Gray.shader,它會去尋找Unlit - Transparent Colored Gray (SoftClip).shader,而後沒找到就默認回nlit - Transparent Colored .shader,這下好辦了,咱們複製一份Unlit - Transparent Colored Gray.shader,更改它的名字爲Unlit - Transparent Colored Gray.shader,而後打開它的代碼:blog

Shader "Unlit/Transparent Colored Gray"
{
	Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
	}

將最頂上一行修改下名字:圖片

Shader "Unlit/Transparent Colored Gray (SoftClip)"
{
	Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
	}

而後回過頭來再看看顯示:ip

灰色顯示成功。開發

 

 

咱們要代碼控制它灰色怎麼操做呢?get

Color bgColor = item.FindChild(itemName +"/bgImage").GetComponent<UISprite>().color;
bgColor.r = 0;
item.FindChild(itemName + "/bgImage").GetComponent<UISprite>().color = bgColor;

 

 

 

目前又發現一個新的問題:UIScroll沒有裁切圖片,形成邊緣顯示出來,還在找解決辦法!

相關文章
相關標籤/搜索