如果图像没有太大差异,以至于可以假设您将在一个区域中绘制一个非常纯色的字符串,您可以使用以下解决方案。
您可以首先使用一种算法来计算与另一种颜色最不同的颜色,如下所示:
public static byte MostDifferent (byte original) {
if(original < 0x80) {
return 0xff;
} else {
return 0x00;
}
}
public static Color MostDifferent (Color original) {
byte r = MostDifferent(original.R);
byte g = MostDifferent(original.G);
byte b = MostDifferent(original.B);
return Color.FromArgb(r,g,b);
}
现在我们已经完成了,我们必须计算将绘制string 的区域内的平均颜色。您可以在Bitmap 级别执行此操作:
public static unsafe Color AverageColor (Bitmap bmp, Rectangle r) {
BitmapData bmd = bmp.LockBits (r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int s = bmd.Stride;
int cr = 0;
int cg = 0;
int cb = 0;
int* clr = (int*)(void*)bmd.Scan0;
int tmp;
int* row = clr;
for (int i = 0; i < r.Height; i++) {
int* col = row;
for (int j = 0; j < r.Width; j++) {
tmp = *col;
cr += (tmp >> 0x10) & 0xff;
cg += (tmp >> 0x08) & 0xff;
cb += tmp & 0xff;
col++;
}
row += s>>0x02;
}
int div = r.Width * r.Height;
int d2 = div >> 0x01;
cr = (cr + d2) / div;
cg = (cg + d2) / div;
cb = (cb + d2) / div;
bmp.UnlockBits (bmd);
return Color.FromArgb (cr, cg, cb);
}
最后,算法首先测量要绘制字符串的矩形,然后确定最不同的颜色,最后用该颜色绘制字符串:
public static void DrawColorString (this Graphics g, Bitmap bmp, string text, Font font, PointF point) {
SizeF sf = g.MeasureString (text, font);
Rectangle r = new Rectangle (Point.Truncate (point), Size.Ceiling (sf));
r.Intersect (new Rectangle(0,0,bmp.Width,bmp.Height));
Color brsh = MostDifferent (AverageColor (bmp, r));
g.DrawString (text, font, new SolidBrush (brsh), point);
}
现在您可以调用该方法,例如:
Bitmap bmp = new Bitmap("Foo.png");
Graphics g = Graphics.FromImage(bmp);
g.DrawColorString (bmp, "Sky", new Font ("Arial", 72.0f), new PointF (600.0f, 150.0f));
g.DrawColorString (bmp, "Sand", new Font ("Arial", 72.0f), new PointF (600.0f, 450.0f));
bmp.Save ("result.jpg");
这个结果例如: