shader
cg
Shader "Custom/Brightness_Saturation_And_Contrast"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Brightness ("Brightess", Float) = 1.0
_Saturation ("Saturation", Float) = 1.0
_Contrast ("Contrast", Float) = 1.0
}
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct a2f
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
half _Brightness;
half _Saturation;
half _Contrast;
v2f vert (a2f v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//采样
fixed4 renderTex = tex2D(_MainTex, i.uv);
//亮度
fixed3 finalColor = renderTex.rgb * _Brightness;
//饱和度
fixed luminance = 0.2125 * renderTex.r + 0.7154 * renderTex.g + 0.0721 * renderTex.b; //计算该像素的亮度值
fixed3 luminanceColor = fixed3(luminance, luminance, luminance); //创建饱和度为0的颜色
finalColor = lerp(luminanceColor, finalColor, _Saturation);
//对比度
fixed3 avgColor = fixed3(0.5, 0.5, 0.5);
finalColor = lerp(avgColor, finalColor, _Contrast);
return fixed4(finalColor, renderTex.a);
}
ENDCG
}
}
}
通过组件进行调用
csharp
public class ColorAdjust : MonoBehaviour
{
private static readonly int Brightess = Shader.PropertyToID("_Brightess");
private static readonly int Saturation = Shader.PropertyToID("_Saturation");
private static readonly int Contrast = Shader.PropertyToID("_Contrast");
/// <summary>
/// 颜色材质
/// </summary>
public Material colorMaterial;
public void Render(RenderTexture src, RenderTexture dest, float brightess, float saturation, float contrast)
{
if (colorMaterial == null) {
Debug.LogError("材质球为空");
return;
}
colorMaterial.SetFloat(Brightess, brightess);
colorMaterial.SetFloat(Saturation, saturation);
colorMaterial.SetFloat(Contrast, contrast);
Graphics.Blit(src, dest, colorMaterial);
}
}
调用
csharp
ColorAdjust colorAdjust = self.RawImage.GetComponent<ColorAdjust>();
RenderTexture initRt = RenderTexture.GetTemporary(initTx.width, initTx.height, 0);
RenderTexture destRt = RenderTexture.GetTemporary(initTx.width, initTx.height, 0);
//亮度
colorAdjust.Render(initRt, destRt, value, 1, 1);
//饱和度
colorAdjust.Render(initRt, destRt, 1, value, 1);
//对比度
colorAdjust.Render(initRt, destRt, 1, 1, value);