Last active
December 15, 2015 02:59
-
-
Save peteroupc/5191297 to your computer and use it in GitHub Desktop.
Snippet that generates a color gradient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Written by Peter O. 2013. In the public domain. | |
// http://creativecommons.org/publicdomain/zero/1.0/ | |
Color BlendColors(Color crDst, Color crSrc, byte alpha){ | |
switch(alpha){ | |
case 0x00:return crDst; | |
case 0xFF:return crSrc; | |
default:{ | |
int r,g,b,a; | |
r=crDst.R; | |
g=crDst.G; | |
b=crDst.B; | |
a=crDst.A; | |
return Color.FromArgb((alpha*((int)crSrc.A-a)>>8)+a, | |
(alpha*((int)crSrc.R-r)>>8)+r, | |
(alpha*((int)crSrc.G-g)>>8)+g, | |
(alpha*((int)crSrc.B-b)>>8)+b); | |
} | |
} | |
} | |
Color[] FontGenerateGradient(Color[] src, int szDst){ | |
float step,curstep; | |
int i,j; | |
float[] srcSteps; | |
float srcStep; | |
int thisstep=0; | |
if(src==null) | |
throw new ArgumentNullException("src"); | |
if(szDst<0) | |
throw new ArgumentOutOfRangeException("szDst must be 0 or greater."); | |
Color[] dst=new Color[szDst]; | |
//check trivial cases | |
if(src.Length==1){ | |
for(i=0;i<szDst;i++) | |
dst[i]=src[0]; | |
return dst; | |
} | |
if(src.Length==szDst){ | |
for(i=0;i<szDst;i++) | |
dst[i]=src[i]; | |
return dst; | |
} | |
switch(szDst){ | |
case 0: | |
return dst; | |
case 1: | |
dst[0]=src[0]; | |
return dst; | |
case 2: | |
dst[0]=src[0]; | |
dst[1]=src[src.Length-1]; | |
return dst; | |
default: | |
dst[0]=src[0]; | |
dst[szDst-1]=src[src.Length-1]; | |
break; | |
} | |
step=(float)1.0/(src.Length-1); | |
srcStep=step; | |
srcSteps=new float[src.Length]; | |
srcSteps[0]=0.0f; | |
srcSteps[src.Length-1]=1.0f; | |
for(i=1;i<src.Length-1;i++){ | |
srcSteps[i]=step*i; | |
} | |
step=(float)1.0/(szDst-1); | |
curstep=step; | |
thisstep=0; | |
for(i=1;i<szDst-1;i++,curstep+=step){ | |
float diffFade,diffPoint,t; | |
int alpha; | |
Color thiscol; | |
for(j=thisstep;srcSteps[j+1]<curstep;j++){ | |
thisstep++; | |
} | |
diffFade=srcStep;//srcSteps[thisstep+1]-srcSteps[thisstep]; | |
diffPoint=curstep-srcSteps[thisstep]; | |
t=diffPoint/diffFade; | |
alpha=(int)(t*255); | |
thiscol=BlendColors(src[thisstep],src[thisstep+1],(byte)alpha); | |
dst[i]=thiscol; | |
} | |
return dst; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment