以一定角度

时间:2016-07-29 10:31:49

标签: c# .net bitmap gdi+ system.drawing

我使用以下代码在Image an Angle

的中心绘制文本
Bitmap bmp = new Bitmap(pictureBox1.Image);
using (Graphics g = Graphics.FromImage(bmp)) {
  g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);
  g.RotateTransform(30);
  SizeF textSize = g.MeasureString("hi", font);
  g.DrawString("hi", font, Brushes.Red, -(textSize.Width / 2), -(textSize.Height / 2));
}

我需要像这样在整个图像上拼贴文本

enter image description here

我知道我可以增加坐标并使用Loop.I有

Bitmap bmp = new Bitmap(pictureBox1.Image);
            for (int i = 0; i < bmp.Width; i += 20)
            {
                for (int y = 0; y < bmp.Height; y += 20)
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);                      
                        g.RotateTransform(30);
                        SizeF textSize = g.MeasureString("my test image", DefaultFont);
                        g.DrawString("my test image", DefaultFont, Brushes.Yellow, i, y);

                    }
                }
            }
            pictureBox1.Image = bmp;

这会产生以下结果

enter image description here

如何通过正确测量绘制区域来正确放置文本。可以采用更好更快的方法。

2 个答案:

答案 0 :(得分:1)

您正在将文本插入页面的中心 这意味着你的图像0,0坐标是50%,是另一个图像的50%

如果你想得到你想要的结果,我建议你以25%的块为单位划分图像宽度,以获得建议的16个块。然后在每个块的中心添加其中一个文本图像。

请记住,当您添加图像并且希望图像从点而不是从点0,0(这是您的情况下发生的情况)的原点旋转时,您需要明确说明它,请认为该命令是{{1或者那行中的某些东西,

答案 1 :(得分:1)

调用其他TranslateTransform将文本移动到您想要的位置,然后在(0,0)坐标处使用DrawString绘制文本。这将围绕其自己的中心旋转每个文本,而不是围绕段落的中心旋转文本。

Bitmap bmp = new Bitmap(pictureBox1.Image);
Graphics g = Graphics.FromImage(bmp);
String text = "TextTile";

Font font = new Font(DefaultFont.Name, 20);
SizeF size = g.MeasureString(text, font);
int textwidth = size.ToSize().Width;
int textheight = size.ToSize().Height;

int y_offset = (int)(textwidth * Math.Sin(45 * Math.PI / 180.0));

//the sin of the angle may return zero or negative value, 
//it won't work with this formula
if (y_offset >= 0)
{
    for (int x = 0; x < bmp.Width; x += textwidth)
    {
        for (int y = 0; y < bmp.Height; y += y_offset)
        {
            //move to this position
            g.TranslateTransform(x, y);

            //draw text rotated around its center
            g.TranslateTransform(textwidth, textheight);
            g.RotateTransform(-45);
            g.TranslateTransform(-textwidth, -textheight);
            g.DrawString(text, font, Brushes.Yellow, 0, 0);

            //reset
            g.ResetTransform();
        }
    }
}

pictureBox1.Image = bmp;

上面的示例使用大小为20的较大字体。您可以将其设置为使用DefaultFont.size。它使用45度角。

相关问题