图片内发光

作者:追风剑情 发布于:2019-1-27 14:55 分类:Shader

一、工程截图

2222.png

二、Shader代码


  1. Shader "Custom/Glow"
  2. {
  3. Properties
  4. {
  5. _MainTex ("Texture", 2D) = "white" {}
  6. _GlowColor ("Glow Color", Color) = (0, 1, 0, 1)
  7. _GlowSize ("Glow Size", Range(0.01, 1)) = 0.2
  8. //图片高宽比
  9. _AspectRatio ("Aspect Ratio", Float) = 1
  10. }
  11. SubShader
  12. {
  13. Tags { "RenderType"="Opaque" }
  14. LOD 100
  15.  
  16. Pass
  17. {
  18. CGPROGRAM
  19. #pragma vertex vert
  20. #pragma fragment frag
  21.  
  22. #include "UnityCG.cginc"
  23.  
  24. struct appdata
  25. {
  26. float4 vertex : POSITION;
  27. float2 uv : TEXCOORD0;
  28. };
  29.  
  30. struct v2f
  31. {
  32. float2 uv : TEXCOORD0;
  33. float4 vertex : SV_POSITION;
  34. };
  35.  
  36. sampler2D _MainTex;
  37. float4 _MainTex_ST;
  38. fixed4 _GlowColor;
  39. half _GlowSize;
  40. fixed _AspectRatio;
  41.  
  42. v2f vert (appdata v)
  43. {
  44. v2f o;
  45. o.vertex = UnityObjectToClipPos(v.vertex);
  46. o.uv = TRANSFORM_TEX(v.uv, _MainTex);
  47. return o;
  48. }
  49.  
  50. fixed4 frag (v2f i) : SV_Target
  51. {
  52. fixed4 col = tex2D(_MainTex, i.uv);
  53.  
  54. fixed center = 0.5;
  55. //平移原点到图片中心
  56. fixed2 uv = i.uv - fixed2(center, center);
  57. uv.x = abs(uv.x);
  58. uv.y = abs(uv.y);
  59.  
  60. fixed glowSizeX = _GlowSize * _AspectRatio;
  61. fixed glowSizeY = _GlowSize;
  62.  
  63. //内矩形最大角
  64. fixed2 innerMax = fixed2(center-glowSizeX, center-glowSizeY);
  65.  
  66. //普通版代码
  67. /* if (uv.x >= innerMax.x || uv.y >= innerMax.y)
  68. {
  69. fixed t = 0;
  70. if (uv.x > innerMax.x && uv.y > innerMax.y) {
  71. if ((uv.x - innerMax.x)/_AspectRatio > uv.y - innerMax.y) {
  72. t = (uv.x - innerMax.x)/glowSizeX;
  73. }else{
  74. t = (uv.y - innerMax.y)/glowSizeY;
  75. }
  76. }else if(uv.x >= innerMax.x) {
  77. t = (uv.x - innerMax.x)/glowSizeX;
  78. }else if(uv.y >= innerMax.y) {
  79. t = (uv.y - innerMax.y)/glowSizeY;
  80. }
  81. return col*(1-t) + _GlowColor*t;
  82. } */
  83.  
  84. //优化后的代码(即,对上面版本的代码消除流程控制)
  85. fixed margin = max(step(innerMax.x, uv.x), step(innerMax.y, uv.y));
  86. fixed t = 0;
  87. fixed tx = (uv.x - innerMax.x)/glowSizeX;
  88. fixed ty = (uv.y - innerMax.y)/glowSizeY;
  89.  
  90. fixed innerCorner = step(innerMax.x, uv.x) * step(innerMax.y, uv.y);
  91. fixed leftRight = step(innerMax.x, uv.x);
  92. fixed topBottom = step(innerMax.y, uv.y);
  93. fixed nearX = step(uv.y - innerMax.y, (uv.x - innerMax.x)/_AspectRatio);
  94.  
  95. fixed tc = tx * nearX + ty * (1 - nearX);//当uv坐标落在四个角时的插值t
  96. t = tc * innerCorner + tx * (1-innerCorner) * leftRight + ty * (1-innerCorner) * topBottom;
  97.  
  98. col = col * (1-margin) + (col*(1-t) + _GlowColor*t) * margin;
  99. return col;
  100. }
  101. ENDCG
  102. }
  103. }
  104. }


效果, 通过调整GlowSize值来调整发光边缘大小

1.gif

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号