思路: 寻找边界点,均值平滑:
Shader “UI-Effect/ImgOutline” {
Properties {
// [NoScaleOffset] _MainTex (“Main Texture”, 2D) = “black” {}
_OutlineWidth("Outline Width", Range(0, 10)) = 3.0
_OutlineColor("Outline Color", Color) = (1,1,0,1)
_ThresholdEnd("Outline Threshold", Range(0, 1)) = 0.25
_OutlineSmoothness("Outline Smoothness", Range(0, 1)) = 1.0
_Color ("Color ", Color) = (1, 1, 1, 1)
}
SubShader {
Tags { "Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
}
Cull Off
ZWrite Off
Lighting Off
Blend One OneMinusSrcAlpha
Pass {
Name "Outline"
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 color : Color;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float vertexAlpha : Color;
};
v2f vert (appdata v)
{
v2f o = (v2f)0;
o.uv = v.uv;
o.vertex = UnityObjectToClipPos(v.vertex);
o.vertexAlpha = v.color.a;
return o;
}
sampler2D _MainTex;
float _OutlineWidth;
float4 _OutlineColor;
float4 _MainTex_TexelSize;
float _ThresholdEnd;
float _OutlineSmoothness;
fixed4 _Color;
fixed4 frag (v2f i) : SV_Target
{
float4 mainCol = tex2D(_MainTex, i.uv);
// 使用自己的alpha数值, 不然计算之后的颜色的alpha值也会加进来
mainCol.rgb = _Color.rgb;
mainCol.rgb *= mainCol.a;
// 计算中心像素的alpha ,通过比较周围4个像素点的alpha,判断是不是边缘点
float xOffset = _MainTex_TexelSize.x * _OutlineWidth / (1024 * _MainTex_TexelSize.x);
float yOffset = _MainTex_TexelSize.y * _OutlineWidth / (1024 * _MainTex_TexelSize.x);
float pixelCenter = tex2D(_MainTex, i.uv).a;
float4 centerLod = float4(i.uv, 0, 0);
float pixelTop = tex2Dlod(_MainTex, centerLod + float4(0, yOffset, 0, 0)).a;
float pixelBottom = tex2Dlod(_MainTex, centerLod + float4(0, -yOffset, 0, 0)).a;
float pixelLeft = tex2Dlod(_MainTex, centerLod + float4(-xOffset, 0, 0, 0)).a;
float pixelRight = tex2Dlod(_MainTex, centerLod + float4(xOffset, 0, 0, 0)).a;
float numSamples = 1;
//float average = (pixelTop + pixelBottom + pixelLeft + pixelRight) * i.vertexAlpha / numSamples;
fixed average = (pixelTop + pixelBottom + pixelLeft + pixelRight + pixelCenter) / 5;
float thresholdStart = _ThresholdEnd * (1.0 - _OutlineSmoothness);
float outlineAlpha = saturate((average - thresholdStart) / (_ThresholdEnd - thresholdStart)) - pixelCenter;
mainCol.rgba = lerp(mainCol, _OutlineColor, outlineAlpha);
return mainCol;
}
ENDCG
}
}
}文章来源:https://www.toymoban.com/news/detail-521897.html
文章来源地址https://www.toymoban.com/news/detail-521897.html
到了这里,关于Unity文字描边的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!