FontMapper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using SkiaSharp;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Text;
  19. namespace Topten.RichTextKit
  20. {
  21. /// <summary>
  22. /// The FontMapper class is responsible for mapping style typeface information
  23. /// to an SKTypeface.
  24. /// </summary>
  25. public class FontMapper
  26. {
  27. /// <summary>
  28. /// Constructs a new FontMapper instnace
  29. /// </summary>
  30. public FontMapper()
  31. {
  32. }
  33. /// <summary>
  34. /// Maps a given style to a specific typeface
  35. /// </summary>
  36. /// <param name="style">The style to be mapped</param>
  37. /// <param name="ignoreFontVariants">Indicates the mapping should ignore font variants (use to get font for ellipsis)</param>
  38. /// <returns>A mapped typeface</returns>
  39. public virtual SKTypeface TypefaceFromStyle(IStyle style, bool ignoreFontVariants)
  40. {
  41. // Extra weight for superscript/subscript
  42. int extraWeight = 0;
  43. if (!ignoreFontVariants && (style.FontVariant == FontVariant.SuperScript || style.FontVariant == FontVariant.SubScript))
  44. {
  45. extraWeight += 100;
  46. }
  47. // Get the typeface
  48. return SKTypeface.FromFamilyName(
  49. style.FontFamily,
  50. (SKFontStyleWeight)(style.FontWeight + extraWeight),
  51. style.FontWidth,
  52. style.FontItalic ? SKFontStyleSlant.Italic : SKFontStyleSlant.Upright
  53. ) ?? SKTypeface.CreateDefault();
  54. }
  55. /// <summary>
  56. /// The default font mapper instance.
  57. /// </summary>
  58. /// <remarks>
  59. /// The default font mapper is used by any TextBlocks that don't
  60. /// have an explicit font mapper set (see the <see cref="TextBlock.FontMapper"/> property).
  61. ///
  62. /// Replacing the default font mapper allows changing the font mapping
  63. /// for all text blocks that don't have an explicit mapper assigned.
  64. /// </remarks>
  65. public static FontMapper Default = new FontMapper();
  66. }
  67. }