Unity Texture2D create rounded corners

Mansa picture Mansa · Apr 17, 2015 · Viewed 7.9k times · Source

I am making a game in unity and am having this issue. The users can upload an profile image from there device to my backenserver to personalize there account. This part is working just fine, but...

The picture is square rectangle but I would like to show the image as round, or with rounded corners when it is showed in the game? Can this be done in Unity with c# or is this not possible?

Answer

Chris Mantle picture Chris Mantle · Apr 17, 2015

It's relatively simple. You need to use alpha masking, which is a method of making selected parts of some geometry transparent using alpha blending.

You need to create an alpha mask. This is an image that is white where you want the user's profile picture to be fully opaque, and black where you want it to be fully transparent (around the corners, in your case). If you use an 8-bit alpha mask, you can use the 254 shades of grey between black and white to fully blend between opaque and transparent, giving your corners that nice, rounded look you're shooting for.

Create your alpha mask in the 2D graphics editor of your choice. In your Unity shader, bind both the user's profile picture and your alpha mask. Create a pixel shader, and in it, take the RGB component from the user's profile picture, and the alpha value from your mask:

sampler2D userProfilePic;
sampler2D roundedCornersAlphaMask;

struct PS_IN
{
    float4 position : SV_POSITION;
    float2 texCoord : TEXCOORD0;
};

float4 PixelShader(PS_IN input) : SV_Target
{
    fixed4 profilePicSample = tex2D(userProfilePic, input.texCoord);
    fixed4 alphaMaskSample = tex2D(roundedCornersAlphaMask, input.texCoord);

    return fixed4(
        profilePicSample.r,
        profilePicSample.g,
        profilePicSample.b,
        alphaMaskSample.r);
}

This seems to be a more detailed article on what you want to do - it has a more complete shader example, too: Unity3D: Unlit Alpha Mask Shader