项目分享:https://github.com/Claymoreno1/RenderTexture
2018年11月9日,星期五,晚上终于有时间玩switch了,不过在此之前,先搞一波Unity
目前,我已经添加了一些基本功能,亮度对比度饱和度,我都是用shader完成的,目前功能很少,这个shader也很简单,和屏幕后处理用的一毛一样
Shader "myshaders/BSC"
{
Properties
{
_MainTex ("_MainTex", 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 v2a
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 pos : SV_POSITION;
};
v2f vert (v2a v)
{
v2f o;
o.pos = UnityObjectToClipPos(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
}
这次真正的重点在于C#部分,目前已经有打开文件,更改亮度饱和度对比度,滑动滚落缩放,左键拖拽图片这几个功能
在通过OpenFileDialog得到文件路径之后,采用WWW方法拿到texture
WWW www = new WWW(path);
yield return www;
texture = www.texture;
通过Graphics.Blit把shader处理之后的texture输出到RenderTexture,再冲RT中读到texture对象中
RenderTexture Disttexture = new RenderTexture(texture.width, texture.height, 0);
Graphics.Blit(texture, Disttexture, material);
int width = Disttexture.width;
int height = Disttexture.height;
Viewtexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
RenderTexture.active = Disttexture;
Viewtexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
Viewtexture.Apply();
需要特别注意的是,不要在Asset中提前创建RT,因为无法再代码中修改它的大小,还有一定要初始化代码创建的RT,万物皆对象。
完整的文件加载与图像处理C#代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Windows.Forms;
public class transmit :PostEffectsBase
{
public Canvas uicanvas;
public UnityEngine.UI.Image image;
private Texture2D texture;
public Shader processshader;
private Material processmat;
private Material material
{
get
{
processmat = CheckShaderAndCreateMaterial(processshader, processmat);
return processmat;
}
}
private Texture2D Viewtexture;
private string path;
[Range(0.0f, 3.0f