Search code examples
c#graphicsrotationdrawstringrotatetransform

C# Rotated DrawString from Right Corner


I am trying to draw text on an image from top right corner towards the bottom left corner. My code mess up the positioning of drawstring. so far this code drawing like this but I need help to draw text between these red lines.

enter image description here

string img_src = "F:\\blank_imge.jpg";
    System.Drawing.Image selected_img = System.Drawing.Image.FromFile(img_src);
    using(Graphics gr = Graphics.FromImage(selected_img))
    {
        Font font = new Font("Arial", 2.0f);
        int x = selected_img.Width;
        int y = 0;
        for (int b = 1; b <= 5; b++)
        {
             GraphicsState state = gr.Save();
             gr.ResetTransform();
             int opacity = 35;
             string txt = "watermark";
             using (Brush brush = new SolidBrush(Color.FromArgb(opacity, 255, 255, 255)))
             {
                   SizeF textSize = gr.MeasureString("watermark", font);
                   gr.RotateTransform(45);
                   gr.SmoothingMode = SmoothingMode.HighQuality;
                   gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                   gr.DrawString(txt, font, brush, new PointF(x - textSize.Width, y));
             }

             y = y + 25;
             gr.Restore(state);
        }    
       selected_img.Save("F:\\watermarked.jpg");
    }

Solution

  • I'd write it more like this. There are lots of little changes in there...look closely!

            using (Graphics gr = Graphics.FromImage(selected_img))
            {
                int y = -50;
                int opacity = 127; // 0 to 255
                string txt = "watermark";
                int x = selected_img.Width;
                GraphicsState state = gr.Save();
                gr.ResetTransform();
                gr.TranslateTransform(selected_img.Width / 2, selected_img.Height / 2);
                gr.RotateTransform(45);
                gr.SmoothingMode = SmoothingMode.HighQuality;
                gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                using (Font font = new Font("Arial", 14.0f))
                {
                    SizeF textSize = gr.MeasureString(txt, font);
                    using (Brush brush = new SolidBrush(Color.FromArgb(opacity, Color.DarkGray)))
                    {
                        for (int b = 1; b <= 5; b++, y += 25)
                        {
                            gr.DrawString(txt, font, brush, new PointF(-(textSize.Width / 2), y));
                        }
                    }
                }
                gr.Restore(state);
            }