VB.NET GDI+ 实现图像中指定角度旋转字符串的方法求助
问题根源说明
StringFormat类仅用于配置文本的对齐方式、换行规则、字符间距等排版属性,本身不具备任何坐标旋转能力。GDI+体系下的图像旋转效果,完全依托Graphics对象的坐标变换能力实现,不存在在StringFormat中配置旋转参数的实现路径。
核心实现逻辑
- 旋转变换的作用域是当前
Graphics对象上的所有后续绘制内容,必须按固定顺序执行操作,否则会出现文本位置错位、其他未旋转的文本也被倾斜的问题。 - 单段带旋转的文本绘制流程:
- 调用
TranslateTransform将坐标系原点平移到文本计划绘制的锚点位置 - 调用
RotateTransform传入目标旋转角度(正值为顺时针旋转) - 调用
TranslateTransform反向平移相同距离,抵消初始平移的偏移量 - 执行原有的
DrawString逻辑绘制文本 - 调用
ResetTransform将坐标系恢复为初始状态,隔离不同文本的旋转效果
- 调用
适配需求的代码修改
保留原代码中的字体、颜色、锚点位置、居中对齐规则,仅按需求调整Select Case块内的绘制逻辑,替换后的代码如下:
Select Case shapecode Case "K-00" Graphics.ResetTransform() Graphics.DrawString(A, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(470, 90), drawformat) Case "K-11" Graphics.ResetTransform() ' 绘制无旋转的文本A Graphics.DrawString(A.ToString, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(843, 128), drawformat) ' 绘制旋转90度的文本B,锚点沿用原设定的(457,124) Graphics.TranslateTransform(457, 124) Graphics.RotateTransform(90) Graphics.TranslateTransform(-457, -124) Graphics.DrawString(B.ToString, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(457, 124), drawformat) Graphics.ResetTransform() Case "K-21" Graphics.ResetTransform() ' 绘制无旋转的文本A Graphics.DrawString(A.ToString, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(75, 139), drawformat) ' 绘制旋转45度的文本B,锚点沿用原设定的(467,124) Graphics.TranslateTransform(467, 124) Graphics.RotateTransform(45) Graphics.TranslateTransform(-467, -124) Graphics.DrawString(B.ToString, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(467, 124), drawformat) ' 绘制旋转90度的文本C,锚点沿用原设定的(859,139) Graphics.TranslateTransform(859, 139) Graphics.RotateTransform(90) Graphics.TranslateTransform(-859, -139) Graphics.DrawString(C.ToString, New Font("Arial", 50, FontStyle.Regular), New SolidBrush(Color.Black), New Point(859, 139), drawformat) Graphics.ResetTransform() End Select
补充注意事项
- 旋转角度的方向规则:
RotateTransform传入正角度时为顺时针旋转,负角度为逆时针旋转,若实际绘制效果和预期方向相反,直接调整角度的正负值即可。 - 每段旋转绘制完成后必须调用
ResetTransform复位坐标系,否则后续绘制的所有内容都会继承上一次的旋转角度,出现位置错位。 - 原代码中保存文件时指定后缀为
.bmp,但实际使用的编码格式为ImageFormat.Jpeg,若需要匹配文件后缀,可将保存参数替换为ImageFormat.Bmp,避免文件格式读取异常。
内容的提问来源于stack exchange,提问作者maxlevel2011
相关产品推荐
相关产品推荐

