图片的灰度处理(Unity Shader)

图片变灰处理

分享一个图片变灰处理的着色器

先看一下效果图吧:


图片的灰度处理(Unity Shader)_第1张图片

Shader "Unlit/Grey"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
	}
	SubShader
	{
		Tags{"RenderType"="Opaque"}
		LOD 100
		pass{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"
			struct a2v{
				float4 vertex:POSITION;
				float2 uv:TEXCOORD0;
				//获取当前实例纹理的颜色值
				fixed4 color_v:COLOR;
			};
			struct v2f{
				float4 pos:SV_POSITION;
				float2 uv:TEXCOORD0;
				//存储顶点着色器传递过来的纹理的颜色
				fixed4 color_f:COLOR;
			};
			sampler2D _MainTex;
			float4 _MainTex_ST;
			v2f vert(a2v v){
				v2f o;
				o.pos=UnityObjectToClipPos(v.vertex);
				o.uv=TRANSFORM_TEX(v.uv,_MainTex);
				o.color_f=v.color_v;
				return o;
			}
			fixed4 frag(v2f i):SV_TARGET{
				fixed4 col;
				//根据当前图片的颜色判断是否置灰
				if (i.color_f.r<0.001f){
				    //对当前图片的纹理采样
					col=tex2D(_MainTex,i.uv);
					float grey=dot(col,float3(0.299, 0.587, 0.114));
					col.rgb=float3(grey,grey,grey);
				}else{
					col=tex2D(_MainTex,i.uv);
				}
				return col;
			};
			ENDCG
		}
	}
}

脚本中调用如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GreyTest : MonoBehaviour {
	public Image image01;
	public Image image02;
	Color c1 = new Color (0, 1, 1, 1);
	Color c2 = new Color (1, 1, 1, 1);
	int index = 0;
	// Update is called once per frame
	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			if (index % 2 == 0) {
				image01.color = c1;
				image02.color = c1;
			} else {
				image01.color = c2;
				image02.color = c2;
			}
			index++;
		}
	}
}

在属性面板中,将材质赋给需要灰度处理的图片,如下:


图片的灰度处理(Unity Shader)_第2张图片

更多内容,欢迎关注 :


! 图片的灰度处理(Unity Shader)_第3张图片

你可能感兴趣的:(UnityShader)