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

如何根据字符串尺寸自动调整Image大小,并根据字符串宽度自动填充Rectangle?

嘿,我来帮你搞定这两个需求!咱们一步步优化你的代码,实现自动适配字符串的Rectangle,还能让Image跟着文字尺寸调整大小:

解决方案:自动适配字符串的Rectangle与Image尺寸调整

一、让Rectangle自动适配字符串宽度

要实现这个,核心是先拿到字符串的实际绘制尺寸,再根据这个尺寸来创建Rectangle,还可以加些内边距让文字看起来更舒服:

  • 先用Graphics.MeasureString()算出字符串的宽高(注意要用和绘制时一样的字体,不然尺寸不准)
  • 给文字加上内边距,算出Rectangle的最终大小
  • 根据图片尺寸和矩形大小,确定矩形的位置(比如你原来的右上角位置,就用图片宽度减去矩形宽度来算X坐标)

二、根据字符串尺寸自动调整Image大小

如果数字太长不想被截断,咱们可以让图片跟着扩展:

  • 先算出字符串需要的总空间(文字尺寸+内边距)
  • 对比原图片的尺寸,确定新图片的大小(比如原图片32x32,数字长的话就加宽图片)
  • 把原图片画到新的Bitmap上,再在合适位置绘制带背景的文字

修改后的完整代码

Public Class test
    Public Sub New()
        InitializeComponent()
        NavButton3.Glyph = ImgNotif(NavButton3.Glyph, "99") ' 试试换成"1234"看看效果
    End Sub

    Private Function ImgNotif(srcImg As Image, num As String) As Image
        ' 自定义内边距,让文字和红色背景之间有间隙,更美观
        Dim padding As Integer = 2
        
        ' 创建临时Graphics来测量字符串的实际尺寸
        Using tempG As Graphics = Graphics.FromHwnd(IntPtr.Zero)
            ' 用当前字体测量字符串的宽高
            Dim textSize As SizeF = tempG.MeasureString(num, Me.Font)
            
            ' 计算矩形的大小:文字尺寸 + 两倍内边距(左右、上下都留空)
            Dim rectWidth As Integer = CInt(Math.Ceiling(textSize.Width)) + padding * 2
            Dim rectHeight As Integer = CInt(Math.Ceiling(textSize.Height)) + padding * 2

            ' 确定矩形的位置:右上角对齐,你可以根据需求改位置
            Dim rectX As Integer = srcImg.Width - rectWidth
            Dim rectY As Integer = srcImg.Height - rectHeight

            ' 如果字符串太长,扩展图片宽度,避免文字被截断
            Dim newImgWidth As Integer = Math.Max(srcImg.Width, rectX + rectWidth)
            Dim newImgHeight As Integer = srcImg.Height

            ' 创建适配后的新Bitmap
            Dim bmp As New Bitmap(newImgWidth, newImgHeight)
            Using g As Graphics = Graphics.FromImage(bmp)
                ' 先把原图片绘制到新Bitmap上
                g.DrawImage(srcImg, 0, 0)

                ' 创建适配字符串的Rectangle
                Dim rect As New Rectangle(rectX, rectY, rectWidth, rectHeight)
                ' 填充红色背景
                g.FillRectangle(Brushes.OrangeRed, rect)
                ' 绘制白色文字,位置是矩形左上角加上内边距
                g.DrawString(num, Me.Font, Brushes.White, rectX + padding, rectY + padding)
            End Using
            Return bmp
        End Using
    End Function
End Class

小提示

  • 如果你不想把红色矩形放在右上角,只需要调整rectX和rectY的计算方式就行,比如放在左上角就设为rectX=0, rectY=0
  • 内边距padding的值可以随便调,觉得挤就加大点,宽松就调小
  • 一定要用和绘制时相同的Font来测量字符串,不然会出现尺寸不准的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:39:23