Unity技术分享

shader之调整屏幕的亮度、饱和度和对比度

2017-11-23  本文已影响139人  陈_筱英

1.对于屏幕处理效果都要继承自PostEffectsBase,新建一份c#脚本BrightnessSaturationAndContrast(需挂在摄像机上)

public class BrightnessSaturationAndContrast : PostEffectsBase {

public Shader briSatConShader;

private Material briSatConMaterial;

public Material material {

get {

briSatConMaterial = CheckShaderAndCreateMaterial(briSatConShader, briSatConMaterial);

return briSatConMaterial;

}

}

[Range(0.0f, 3.0f)]

public float brightness = 1.0f;

[Range(0.0f, 3.0f)]

public float saturation = 1.0f;

[Range(0.0f, 3.0f)]

public float contrast = 1.0f;

void OnRenderImage(RenderTexture src, RenderTexture dest) {

if (material != null) {

material.SetFloat("_Brightness", brightness);

material.SetFloat("_Saturation", saturation);

material.SetFloat("_Contrast", contrast);

Graphics.Blit(src, dest, material);

} else {

Graphics.Blit(src, dest);

}

}

}

2.新建一份顶点着色器的shader代码

Shader "Unity Shaders Book/Chapter 12/Brightness Saturation And Contrast" {

Properties {

_MainTex ("Base (RGB)", 2D) = "white" {}

_Brightness ("Brightness", Float) = 1

_Saturation("Saturation", Float) = 1

_Contrast("Contrast", Float) = 1

}

SubShader {

Pass {

ZTest Always Cull Off ZWrite Off

CGPROGRAM

#pragma vertex vert

#pragma fragment frag

#include "UnityCG.cginc"

sampler2D _MainTex;

half _Brightness;

half _Saturation;

half _Contrast;

struct v2f {

float4 pos : SV_POSITION;

half2 uv: TEXCOORD0;

};

v2f vert(appdata_img v) {

v2f o;

o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

o.uv = v.texcoord;

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);

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

}

}

Fallback Off

}

注:该shader要拖动到摄像机脚本BrightnessSaturationAndContrast的briSatConShader变量中运行

实现效果:

上一篇下一篇

猜你喜欢

热点阅读