效果图:
代码:
private void button7_Click(object sender, EventArgs e)
{
Point p = new Point(10,10);
Graphics g = this.panel1.CreateGraphics();
// SizeF sf = g.MeasureString("程序员居然不秃头, 你好意思哈", new Font("宋体", 9));
//之所以不使用MeasureString作为字符串的长度测量, 因为它不准
SizeF sf = TextRenderer.MeasureText(g, "程序员居然不秃头, 你好意思哈", new Font("宋体", 9), new Size(0, 0), TextFormatFlags.NoPadding); //获取真实的字符串像素长度
g.DrawString("程序员居然不秃头, 你好意思哈", this.Font, new SolidBrush(Color.Black), p);
//画下测试的中心点
g.DrawString(".", new Font("宋体",12,FontStyle.Bold), new SolidBrush(Color.Red), new Point((int)Math.Ceiling(sf.Width / 2), (int)Math.Ceiling(sf.Height / 2)));
//将画布中心点平移到尾部
g.TranslateTransform( sf.Width , sf.Height );
//旋转画板
g.RotateTransform(180);
//定点也要对应取负值
g.DrawString("程序员居然不秃头, 你好意思哈", this.Font, new SolidBrush(Color.Blue), new Point(-10, -10));
//回退角度
g.RotateTransform( -180);
//回退画板x,y轴移动过的距离
g.TranslateTransform(- sf.Width , - sf.Height);
//绘制下看看画笔是否恢复原状
g.DrawImage(Image.FromFile(@"C:\Users\WXY\Pictures\MM\155.jpg"), new Point(50, 50));
}
注意 g 的释放