gpt4 book ai didi

c# - 如何使用 System.Drawing 将旋转的字符串绘制为图像?

转载 作者:太空狗 更新时间:2023-10-29 20:28:56 24 4
gpt4 key购买 nike

我正在为图像绘制字符串。图像的大小是动态的,或者换句话说,图像的大小与显示字符串所需的一样大。为实现这一点,我在使用 Graphics.DrawString() 渲染文本之前使用 Graphics.MeasureString() 测量尺寸。

在轮换发挥作用之前一切都很好。到目前为止,我一直在将字符串绘制到位图中并旋转我得到的整个位图。

问题是我的调色板非常有限,而且没有混合色。所以我必须避免任何类型的抗锯齿,这只能通过旋转文本位图使用 InterpolationMode.NearestNeighbor 来实现。虽然这确保不会呈现不需要的颜色,但结果确实非常难看(从用户的角度来看)。

我的想法:应该可以通过使用 Graphics.RotateTransform() 旋转位图并避免剪裁来将文本绘制到位图中,不是吗?

因为我必须首先定义要绘制的图像的大小,并且因为这个大小会随着旋转而增加,所以我不知道如何完成这项工作。

非常感谢任何帮助!

最佳答案

这段代码会给你一个想法:

    public void DrawText(bool debug, Graphics g, string text, Font font, Brush brush, StringFormat format, float x, float y, float width, float height, float rotation)
{
float centerX = width / 2;
float centerY = height / 2;

if (debug)
{
g.FillEllipse(Brushes.Green, centerX - 5f, centerY - 5f, 10f, 10f);
}

GraphicsState gs = g.Save();

Matrix mat = new Matrix();
mat.RotateAt(rotation, new PointF(centerX, centerY), MatrixOrder.Append);

g.Transform = mat;

SizeF szf = g.MeasureString(text, font);

g.DrawString(text, font, brush, (width / 2) - (szf.Width / 2), (height / 2) - (szf.Height / 2), format);

g.Restore(gs);
}

这是一种使用 GraphicsPath 测量旋转文本边界的方法。逻辑很简单,GraphicsPath 将文本转换为点列表,然后计算边界矩形。

    public RectangleF GetRotatedTextBounds(string text, Font font, StringFormat format, float rotation, float dpiY)
{
GraphicsPath gp = new GraphicsPath();

float emSize = dpiY * font.Size / 72;

gp.AddString(text, font.FontFamily, (int)font.Style, emSize, new PointF(0, 0), format);

Matrix mat = new Matrix();
mat.Rotate(rotation, MatrixOrder.Append);

gp.Transform(mat);

return gp.GetBounds();
}

测试代码:

        float fontSize = 25f;
float rotation = 30f;

RectangleF txBounds = GetRotatedTextBounds("TEST TEXT", new Font("Verdana", fontSize, System.Drawing.FontStyle.Bold), StringFormat.GenericDefault, rotation, 96f);

float inflateValue = 10 * (fontSize / 100f);

txBounds.Inflate(inflateValue, inflateValue);

Bitmap bmp = new System.Drawing.Bitmap((int)txBounds.Width, (int)txBounds.Height);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.Clear(Color.White);
DrawText(true, gr, "TEST TEXT", new Font("Verdana", fontSize, System.Drawing.FontStyle.Bold), Brushes.Red, new StringFormat(System.Drawing.StringFormatFlags.DisplayFormatControl), 0, 0, txBounds.Width, txBounds.Height, rotation);
}

关于c# - 如何使用 System.Drawing 将旋转的字符串绘制为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5543988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com