Unity通过shader实现图像转像素画
新建一个无光照shader(我选择了 Create -> Shader -> Unlit Shader),命名为:PixelateShader,双击打开它,粘贴以下内容
Shader "Custom/PixelateShader"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_PixelSize("Pixel Size", Float) = 0.01
}
SubShader
{
Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
LOD 100
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _PixelSize;
v2f vert(appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
float2 uv = i.uv;
// 计算像素化的UV坐标
uv = floor(uv / _PixelSize) * _PixelSize + _PixelSize * 0.5;
fixed4 col = tex2D(_MainTex, uv);
return col;
}
ENDCG
}
}
FallBack "Transparent/Cutout/VertexLit"
}
然后新建一个材质,在 shader 那里选择 Custom/PixelateShader,然后把这个材质拖动到 Image 组件的 Material 上面,调整材质的 Pixel Size 属性,就能将图片变成像素画