我正在 VS2010 中编写 C# 代码以实现以下目标。
我试图在透明位图上绘制文本,但遇到了难看的文本。 下面是三个文本的图片(即 A、B 和 C)
注意:A和C是透明背景,B是白色背景。 问题:
答:我有一个 ARGB 像素格式的位图。我想在里面画一段文字。绘制的文本具有锐利的边缘并且不符合透明度。
B:我写了完全相同的代码,但与 A 的唯一区别是位图中的像素不再透明。 (我将填充一个矩形)。但是,如果您注意文本的像素,您会看到黑色(文本颜色)和白色(背景颜色)的平滑混合。
C:当我在具有透明像素的位图上绘制文本时,这就是我期望的文本外观。
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
//e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, Color.Red)), e.ClipRectangle);
e.Graphics.DrawString("0123456789", new Font("Verdana", 20), Brushes.Red, new PointF(5, 10));
e.Graphics.DrawEllipse(Pens.Black, e.ClipRectangle);
}
// This is a public method, using which I want to save my usercontrol to an image to save to file later.
public Image ToImage(Size size, PixelFormat p)
{
Bitmap b = new Bitmap(Width, Height, p);
using (Graphics g = Graphics.FromImage(b))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
PaintEventArgs e = new PaintEventArgs(g, new Rectangle(0, 0, size.Width, size.Height));
base.OnPaint(e);
this.OnPaint(e);
}
return b;
}
如何使 A 看起来像具有透明背景的 C。我很确定这是可以做到的,因为 photoshop、paint.net 等软件可以很好地处理这个问题。
非常感谢!
数据
最佳答案
绘制文本不会影响目标位图上的 alpha channel ,如果绘制到要混合到其他位图的中间 ARGB 位图,文本将始终看起来像那样。
您需要在绘制文本后操作位图的像素,因此您重新计算每个像素的 alpha 值,使其等于您的灰度文本。您可以在遍历位图(慢)时使用 GetPixel
/PutPixel
组合,也可以使用代码的 unsafe
部分(不安全、指针、快)。
关于c# - 难看的文字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5167937/