如何在C#中旋转矩形形状的文本

3

我已经制作了一个能生成PNG格式二维码图片并输出其中文本的应用程序,但现在我需要将这段文字旋转90度,而我找不到实现这个功能的方法……我认为矩形必须被旋转,因为文字是在这个矩形内部的。

示例: enter image description here

代码:

namespace QR_Code_with_WFA
{
    public void CreateQRImage(string inputData)
    {
        if (inputData.Trim() == String.Empty)
        {
            System.Windows.Forms.MessageBox.Show("Data must not be empty.");
        }

        BarcodeWriter qrcoder = new ZXing.BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new ZXing.QrCode.QrCodeEncodingOptions
            {
                ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
                Height = 250,
                Width = 250
            }
        };

        string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";

        Image image;
        String data = inputData;
        var result = qrcoder.Write(inputData);
        image = new Bitmap(result);
        image.Save(tempFileName);

        System.Diagnostics.Process.Start(tempFileName);

    var result2 = qrcoder.Write(inputData);

    int textWidth = 200, textHeight = 20;
    // creating new bitmap having imcreased width
    var img = new Bitmap(result2.Width + textWidth, result2.Height);

    using (var g = Graphics.FromImage(img))
    using (var font = new Font(FontFamily.GenericMonospace, 12))
    using (var brush = new SolidBrush(Color.Black))
    using (var bgBrush = new SolidBrush(Color.White))
    using (var format = new StringFormat() { Alignment = StringAlignment.Near })
    {
            // filling background with white color
            g.FillRectangle(bgBrush, 0, 0, img.Width, img.Height);
            // drawing your generated image over new one
            g.DrawImage(result, new Point(0,0));
            // drawing text
            g.DrawString(inputData, font, brush,  result2.Width, (result2.Height - textHeight) / 2, format);
    }

    img.Save(tempFileName);
    }
}
2个回答

2

在绘制文本之前,您需要对 Graphics 对象应用 RotateTransform

// Change alignment to center so you don't have to do the math yourself :)
using (var format = new StringFormat() { Alignment = StringAlignment.Center })
{
   ...
   // Translate to the point where you want the text
   g.TranslateTransform(result2.Width, result2.Height / 2);
   // Rotation happens around that point
   g.RotateTransform(-90);
   // Note that we draw on [0, 0] because we translated our coordinates already
   g.DrawString(inputData, font, brush, 0, 0, format);
   // When done, reset the transform
   g.ResetTransform();
}

如果我使用这个,文本将会消失。 - Valip
这是因为您还需要使用Graphics.TranslateTransform,否则您将围绕[0, 0]旋转,因此您的文本将不再可见。我已更新我的答案。 - huysentruitw


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接