2015-05-04 71 views
3

我已經提出了一個應用程序,它生成一個PNG圖像中的QR碼,並從QR圖像中打印出文本,但現在我需要將該文本旋轉90度,沒有辦法做到這一點...我認爲矩形必須旋轉,因爲它在這個矩形內的文字。如何旋轉矩形形狀的文本C#

例子: 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

您需要繪製文本之前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(); 
} 
+0

如果我用這個文本將消失 – Valip

+0

那是因爲你還必須使用'Graphics.TranslateTransform',否則你周圍旋轉[0 ,0],所以你的文字不再可見。更新了我的答案。 –

+1

非常感謝! – Valip