Based on this I am able to determine what color the text should be, given a background.
When I have a background image, I take all the pixels that are under the text and, for each pixel, I calculate the optimal color, black or white. If I have more blacks, the text is drawn in black, else white.
Using for example the IWICBitmap lock:
UINT bs0 = 0, bs1 = 0;
WICInProcPointer ptr0 = 0, ptr1 = 0;
l0->GetDataPointer(&bs0, &ptr0);
l1->GetDataPointer(&bs1, &ptr1);
DWORD* pc0 = (DWORD*)ptr0;
DWORD* pc1 = (DWORD*)ptr1;
int whites = 0;
int blacks = 0;
for (int yy = 0; yy < (int)Height(); yy++)
{
for (int xx = 0; xx < (int)Width() ; xx++)
{
DWORD& w0 = pc0[yy * (int)Width() + xx];
DWORD& w1 = pc1[yy * (int)Width() + xx];
if (w1 == 0) // not under the text
continue;
unsigned char* pCurrPixel = (unsigned char*)&w0;
float red = pCurrPixel[0]/255.0f;
float green = pCurrPixel[1] / 255.0f;
float blue = pCurrPixel[2] / 255.0f;
float alpha = pCurrPixel[3] / 255.0f;
auto cx = ContrastColor({ red,green,blue,alpha }, 1.0f);
if (cx.r > 0.5f)
whites++;
else
blacks++;
nop();
}
}
if (whites > blacks)
{
// This better be white
Col = { 1,1,1,1 };
}
else
{
// This better be black
Col = { 0,0,0,1 };
}
Now this of course will have some problems if the difference between blacks and whites are small. So I'm now trying to find, in the image a better position for the text.
For example, in the image here, the text is better in top right, than in the center.
The question is how to find the optimal text position. I could of course loop the entire image (based on the frame rect of the text) and determine the position that has the bigger difference between blacks and whites.
But, is there a quicker way?