You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET WinForms中DrawString使用StringFormat.Center仍无法居中如何解决

文本在矩形内完美居中的解决方案

你遇到的偏移是GDI+默认文本渲染参数和Graphics对象使用错误导致的,按以下步骤修改即可解决:

核心修改点

  • 不要在OnPaint方法中自行调用CreateGraphics创建绘图对象,直接使用事件参数提供的e.Graphics,避免上下文不一致和资源泄漏
  • 关闭DrawString默认的额外留白,使用排版专用的StringFormat.GenericTypographic作为基础格式配置
  • 开启高精度文本渲染模式,消除字体hinting带来的像素偏移
  • 给StringFormat添加必要的格式标记,禁用不必要的换行和边距计算

修正后完整代码

Sub Main()
    Using x As New Form1()
        x.ShowDialog()
    End Using
End Sub

Imports System.Drawing
Imports System.Drawing.Text
Imports System.Windows.Forms

Public Class Form1
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)
        ' 直接使用事件提供的Graphics对象,不要自行CreateGraphics
        Dim g As Graphics = e.Graphics
        ' 开启高精度文本渲染,可根据需求选择AntiAlias/ClearTypeGridFit
        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit
        
        Dim rect As New Rectangle(3, 3, 15, 15)
        ' 使用排版用的StringFormat,默认无额外留白
        Dim sf As StringFormat = StringFormat.GenericTypographic
        ' 设置居中对齐
        sf.LineAlignment = StringAlignment.Center
        sf.Alignment = StringAlignment.Center
        ' 添加格式标记,避免多余边距计算
        sf.FormatFlags = sf.FormatFlags Or StringFormatFlags.NoWrap Or StringFormatFlags.MeasureTrailingSpaces
        
        ' 绘制文本和矩形
        g.DrawString("0", New Font("Verdana", 6.0!, FontStyle.Regular, GraphicsUnit.Point, 0), Brushes.Black, rect, sf)
        g.DrawRectangle(Pens.HotPink, rect)
    End Sub
End Class

补充说明

如果对精度要求极高,还可以先调用g.MeasureString("0", 字体, 最大宽度, sf)拿到文本的实际像素尺寸,再对绘制矩形的坐标做1像素以内的微调,即可实现完全的像素级居中。

内容的提问来源于stack exchange,提问作者Eviler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:08