Skip to main content
 首页 » 编程设计

c#之无论图像颜色如何,在图像上绘制可见文本

2024年02月06日15lvdongjie

我想使用 DrawString() 在 24bpp 图像上打印文本。问题是如果我选择白色作为文本颜色,文本在较亮的图像区域中几乎看不见。如果我选择红色作为文本颜色,文本在包含更多红色的图像区域中几乎不可见。等等。

我想要实现的是文本在任何情况下都可见。我尝试的是用粗体绘制文本,然后使用相同的字体再次绘制文本。但粗体文本稍宽,因此这不是解决方案。

但是解决方案是什么?有吗?

谢谢!

请您参考如下方法:

如果图像差别不大,以至于人们可以假设您将在一个区域中用纯色绘制字符串,则可以使用以下解决方案。

您可以先使用一种算法来计算与另一种颜色最不同的颜色,如下所示:

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"); 

这个结果例如: