- Home /
What is best way to add transparent padding all around my sprites?
The shader I am working on requires that my sprites have a transparent padding all around them that corresponds to the largest dimension of the sprite.
ie.: If my sprite is 64px high by 32px wide, I need to add a 64px padding all around it
I was hoping to figure out a way to avoid having to add that padding ourselves within our image editing software.
Is there a way to do this inside a shader? I guess it could also be done within a C# script attached to our sprites but the idea here would be to NOT modify the source images.
Thank you for reading.
Is it possible at all to modify a texture's size and content before doing a tex2d lookup?
Answer by toddisarockstar · Feb 19, 2017 at 07:10 PM
public Texture2D oldpic;
public Texture2D newpic;
int padsize;
int i;
int i2;
Color c;
void Start () {
// in the inpector click on your texture and go to the import setting.
// change the texture type to advanced and enable read/write for your texture
padsize = 64;
i = padsize * 2;
//make a new empty texture a bit bigger than your first
newpic = new Texture2D (oldpic.height + i, oldpic.width + i);
//make a loop to paint our new image clear
i = newpic.height;
while (i>0) {i--;
i2=newpic.width;
while(i2>0){i2--;
newpic.SetPixel(i2,i,Color.clear);
}
}
newpic.Apply ();
// copy all the pixels from the first texture into the middle of the new one!!
i = oldpic.height;
while (i>0) {i--;
i2=oldpic.width;
while(i2>0){i2--;
c=oldpic.GetPixel(i2,i);
newpic.SetPixel(i2+padsize,i+padsize,c);
}
}
newpic.Apply ();
}
this approach is better, since it avoids extra computations during runtime
Answer by IgorAherne · Feb 19, 2017 at 07:04 PM
use the following approach when samping the texture by the quad:
0.1
uv is 0%
0.9
uv is 100%
For example
vec2 respecifiedUV = (currentUV) / (0.8) + 0.1;
respecifiedUV = clamp(currentUV(currentUV, 0, 1);
if(respecifiedUV < vec2(0) || respecifiedUV > vec2(1)){
make transparent
}
else {
sample texture with respecifiedUV
}
Anything below 0.1 either on x
or y
should be vec4(0,0,0,0) aka fully transparent color. Use switch() and mix() to avoid branching via if-else (they are very hard for GPUs)
However, if you want to have border "eat-up" edges of your image, then just skip "respecifying uvs" part, and just use if-else or switch and mix