Rotating text by an arbitrary angle (alternative using matrix multiplication)

PDF TIFF SVG JPG C# VB
RotatedText2.vb
  1. ''
  2. '' This code is part of Document Solutions for PDF demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System.IO
  6. Imports System.Drawing
  7. Imports GrapeCity.Documents.Pdf
  8. Imports GrapeCity.Documents.Text
  9. Imports GrapeCity.Documents.Drawing
  10. Imports System.Numerics
  11.  
  12. '' Shows how to use GcPdfGraphics.Transform to rotate a text string
  13. '' (alternative way using matrix multiplication).
  14. '' See also RotatedText.
  15. Public Class RotatedText2
  16. Function CreatePDF(ByVal stream As Stream) As Integer
  17. '' Rotation angle, degrees clockwise:
  18. Dim angle = -45.0F
  19. ''
  20. Dim doc = New GcPdfDocument()
  21. Dim g = doc.NewPage().Graphics
  22. '' Create a text layout, pick a font and font size:
  23. Dim tl = g.CreateTextLayout()
  24. tl.DefaultFormat.Font = StandardFonts.Times
  25. tl.DefaultFormat.FontSize = 24
  26. '' Add a text, and perform layout:
  27. tl.Append("Rotated text.")
  28. tl.PerformLayout(True)
  29. '' Text insertion point at (1",1"):
  30. Dim ip = New PointF(72, 72)
  31. '' Now that we have text size, create text rectangle with top left at insertion point:
  32. Dim rect = New RectangleF(ip.X, ip.Y, tl.ContentWidth, tl.ContentHeight)
  33. '' Rotation center point in the middel of text bounding rectangle:
  34. Dim center = New PointF(ip.X + tl.ContentWidth / 2, ip.Y + tl.ContentHeight / 2)
  35. '' Transformations can be combined by multiplying matrices.
  36. '' Note that matrix multiplication is not commutative -
  37. '' the sequence of operands is important, and is applied from last to first
  38. '' matrices being multiplied:
  39. '' 3) Translate the origin back to (0,0):
  40. '' 2) Rotate around new origin by the specified angle:
  41. '' 1) Translate the origin from default (0,0) to rotation center:
  42. g.Transform =
  43. Matrix3x2.CreateTranslation(-center.X, -center.Y) *
  44. Matrix3x2.CreateRotation((angle * Math.PI) / 180.0F) *
  45. Matrix3x2.CreateTranslation(center.X, center.Y)
  46. '' Draw rotated text and bounding rectangle:
  47. g.DrawTextLayout(tl, ip)
  48. g.DrawRectangle(rect, Color.Black, 1)
  49. '' Remove transformation and draw the bounding rectangle where the non-rotated text would have been:
  50. g.Transform = Matrix3x2.Identity
  51. g.DrawRectangle(rect, Color.ForestGreen, 1)
  52. ''
  53. '' Done:
  54. doc.Save(stream)
  55. Return doc.Pages.Count
  56. End Function
  57. End Class
  58.