C#利用Graphics类绘制进阶--根据文字内容自动生成指定旋转角度图片

public System.Drawing.Image BuildBitmap(string content, System.Drawing.Font font, float py)//根据文字自动生成旋转图片
{
    Bitmap bmp = new Bitmap(1, 1);
    Graphics g = Graphics.FromImage(bmp);

    StringFormat format = new StringFormat(StringFormatFlags.NoClip);
    SizeF sizef = g.MeasureString(content, font, PointF.Empty, format);

    int width = (int)(sizef.Width + 1);
    int height = (int)(sizef.Height + 1);
    bmp.Dispose();
    if (py == 90)//提供0度和90度,其他角度的绘制自行转换宽高值即可
    {
        bmp = new Bitmap(height, width);
    }
    else
    {
        bmp = new Bitmap(width, height);
    }
    g = Graphics.FromImage(bmp);
    //g.Clear(Color.Red);
    //设置画板的坐标原点为中点
    g.TranslateTransform(height, 0);
    //以指定角度对画板进行旋转
    if (py == 90)
    {
        g.RotateTransform(90);
    }

    //让文字变得平滑
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
    g.DrawString(content, font, new SolidBrush(System.Drawing.Color.Black), 0, 0);
    return bmp;
}

猜你喜欢

转载自blog.csdn.net/horseroll/article/details/80497174