Skip to content

Instantly share code, notes, and snippets.

@belzecue
Forked from josephbk117/PixelateImageEffect.cs
Created July 21, 2018 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belzecue/854a9b7eebc94bc7a7918fc177034cd2 to your computer and use it in GitHub Desktop.
Save belzecue/854a9b7eebc94bc7a7918fc177034cd2 to your computer and use it in GitHub Desktop.
Pixelate Image Effect For Unity
using UnityEngine;
[ExecuteInEditMode, RequireComponent(typeof(Camera))]
public class PixelateImageEffect : MonoBehaviour
{
public Material material;
public int pixelDensity = 64;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Vector2 aspectRatioData;
if (Screen.height > Screen.width)
aspectRatioData = new Vector2((float)Screen.width / Screen.height, 1);
else
aspectRatioData = new Vector2(1, (float)Screen.height / Screen.width);
material.SetVector("_AspectRatioMultiplier", aspectRatioData);
material.SetInt("_PixelDensity", pixelDensity);
Graphics.Blit(source, destination, material);
}
}
Shader "Hidden/Pixelation"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
int _PixelDensity;
float2 _AspectRatioMultiplier;
fixed4 frag (v2f i) : SV_Target
{
float2 pixelScaling = _PixelDensity * _AspectRatioMultiplier;
i.uv = round(i.uv * pixelScaling)/ pixelScaling;
return tex2D(_MainTex, i.uv);
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment