65.9K
CodeProject 正在变化。 阅读更多。
Home

VB.NET 实现路径上的文本

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (38投票s)

2006 年 4 月 21 日

1分钟阅读

viewsIcon

147634

downloadIcon

5210

一个用于在路径上绘制文本的 VB.NET 类。

Sample Image - Text_on_Path_with_VBNET.jpg

Sample Image - Text_on_Path_with_VBNET.jpg

引言

我一直在互联网上寻找一种在“路径上”显示“文本”的算法,但我只找到了 Batik SVG Toolkit。它是一个用于显示 SVG 的 Java 项目。SVG 具有在“路径上”显示“文本”的功能,但我只需要文本在路径上的功能。

因此,我开始回忆我以前的数学教育,并编写了第一行代码来计算路径上定义位置的角度。

你还记得 a²+b²=c² 吗?这是解决这个问题的基础。你需要直线上的两个点。

a²+b²=c²

Private Function GetAngle(ByVal _point1 As PointF, _
                 ByVal _point2 As PointF) As Decimal
    Dim c As Decimal
    c = Math.Sqrt((_point2.X - _point1.X) ^ 2 + _
                  (_point2.Y - _point1.Y) ^ 2)
    'Oh yeah good old math a²+b²=c²

    If c = 0 Then
        Return 0
    End If 'We must change the side where the triangle is
    If _point1.X > _point2.X Then 
        Return Math.Asin((_point1.Y - _point2.Y) / c) * _
                                 180 / Math.PI - 180
    Else
        Return Math.Asin((_point2.Y - _point1.Y) / c) * _
                                       180 / Math.PI
    End If

End Function

使用代码

你可以使用 TextOnPath 类来获取带有文本的位图,该文本位于给定的路径上。

路径必须设置为 PathData。你还可以设置 TextPathPositionUnderCenterAbove)并对齐文本(LeftCenterRight)。

Dim _points(5) As PointF
Dim _top As TextOnPath.TextOnPath = New TextOnPath.TextOnPath
Dim _gp As GraphicsPath = New GraphicsPath

_points(0) = New PointF(81, 183)
_points(1) = New PointF(321, 305)
_points(2) = New PointF(333, 622)
_points(3) = New PointF(854, 632)
_points(4) = New PointF(864, 153)
_points(5) = New PointF(562, 224)
_gp.AddCurve(_points)

_top.PathDataTOP = _gp.PathData
_top.FontTOP = New Font("Microsoft Sans Serif", _
                        36, FontStyle.Regular)
_top.FillColorTOP = Color.Black
_top.ColorTOP = Color.White
_top.TextTOP = "Text on path goes around a path"
_top.ShowPath = True
_top.PathAlignTOP = TextOnPath.PathAlign.Center
_top.LetterSpacePercentage = 100
_top.TextPathPosition = TextOnPath.TextPosition.CenterPath

Dim oBitmap as Bitmap 
oBitmap = _top.TextOnPathBitmap

你还可以将新的路径数据作为 SVG 字符串获取,以便在 HTML 中与 Adobe SVG Viewer 一起使用,或在 Corel Draw 或 Adobe Illustrator 中使用。

Dim _svg As String
_svg = _top.GetSVG(1024, 768)

关注点

如果有人对优化此代码有任何想法,请与我联系,并对糟糕的英语和简短的描述表示歉意。这是我的第一篇文章,我仍在学习中。

历史

  • 版本 1.0 发布。
  • 版本 1.01 发布(PathPoint 计算已优化)。
© . All rights reserved.