CSharpMath Documentation

repository·master·Indexed 19 days ago

https://github.com/verybadcat/csharpmath

A C# port of the iosMath LaTeX engine providing cross-platform LaTeX rendering for .NET UI frameworks. It includes implementations for SkiaSharp, Xamarin.Forms, and Avalonia UI, featuring controls like MathView and TextView for mixed text and math. The library supports rendering math to image streams, mathematical evaluation and interpretation via CSharpMath.Evaluation, and tools for extending rendering to new platforms.

Tokens
3.3K
Snippets
9
Records
12
Agent score
66%

What's inside CSharpMath

  1. Extend CSharpMath to new platforms

    master

    There are three primary ways to extend the library to new graphics or font platforms:

    1. Branching off CSharpMath.Rendering (Recommended): Implement the ICanvas interface to connect the library's font lookup (via Typography) to your specific graphics library. Pass this implementation into MathPainter.Draw.
    2. Forking the project: The highest effort path. Requires defining a custom TypesettingContext and implementing IGraphicsContext to allow for completely custom font and graphics libraries.
    3. Building on CSharpMath.SkiaSharp: For other SkiaSharp-supported platforms, pass the SKCanvas from your platform's paint override into MathPainter.Draw.
  2. Render math to an image stream

    master

    You can render math to an image stream using the Painter property of a MathView or TextView, or by using MathPainter directly in SkiaSharp.

    SkiaSharp

    using CSharpMath.SkiaSharp;
    var painter = new MathPainter { LaTeX = @"\frac23" };
    using var png = painter.DrawAsStream();
    // Supports formats like SkiaSharp.SKEncodedImageFormat.Jpeg, Gif, Bmp, etc.

    Xamarin.Forms

    using CSharpMath.SkiaSharp;
    var painter = someMathView.Painter; // or someTextView.Painter
    using var png = painter.DrawAsStream();

    Avalonia

    Note: Due to Avalonia API limitations, you can only render as PNG.

    using CSharpMath.Avalonia;
    var painter = someMathView.Painter; // or someTextView.Painter
    painter.DrawAsPng(someStream);
    using CSharpMath.SkiaSharp;
    var painter = new MathPainter { LaTeX = @"\frac23" };
    using var png = painter.DrawAsStream();
  3. Opt in to the CSharpMath nightly feed

    master

    To access the latest commits from the master branch before they are released, you can use the GitHub NuGet nightly feed.

    1. Generate a GitHub token with the read:packages scope.
    2. Create a NuGet.Config file in your solution folder with your credentials.
    3. Reference the specific package and version (including the CI commit hash) in your .csproj file.
    <!-- NuGet.Config -->
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <packageSources>
            <add key="CSharpMathNightly" value="https://nuget.pkg.github.com/verybadcat/index.json" />
        </packageSources>
        <packageSourceCredentials>
            <CSharpMathNightly>
                <add key="Username" value="YOUR_GITHUB_USERNAME" />
                <add key="ClearTextPassword" value="YOUR_GITHUB_TOKEN" />
            </CSharpMathNightly>
        </packageSourceCredentials>
    </configuration>
    <!-- .csproj -->
    <ItemGroup>
      <PackageReference Include="CSharpMath.SkiaSharp" Version="0.4.2-ci-9db8a6dec29202804764fab9d6f7f19e43c3c083" />
    </ItemGroup>
  4. Display mixed text and math with TextView

    master

    To display a paragraph of normal text containing inline or display math, use the TextView control.

    Delimiters:

    • Inline math: $, \( and \)
    • Display math: $$, \[ and \]

    Usage (XAML):

    <math:TextView LaTeX="Text text text text text \( \frac{\sqrt a}{b} \) text text text text text" />
    <math:TextView LaTeX="Text text text text text \( \frac{\sqrt a}{b} \) text text text text text" />
  5. Create a clickable math button

    master

    Xamarin.Forms

    Use CSharpMath.Forms.MathButton. It wraps a MathView and uses its properties to draw math on the button.

    <math:MathButton x:Name="MathButton">
        <math:MathView x:Name="MathView">
            \frac\sqrt23
        </math:MathView>
    </math:MathButton>

    Avalonia

    Avalonia's standard Button supports arbitrary content. Simply nest a MathView inside a standard Button.

    <Button x:Name="MathButton">
        <math:MathView x:Name="MathView">
            \frac\sqrt23
        </math:MathView>
    </Button>
    <math:MathButton x:Name="MathButton">
        <math:MathView x:Name="MathView">
            \frac\sqrt23
        </math:MathView>
    </math:MathButton>
  6. Manage shared assets in Uno Platform

    master

    To use images or other files across multiple projects in an Uno Platform application, follow these steps:

    1. Add the image file to the Assets directory of a shared project.
    2. Set the build action for the file to Content.
    3. To ensure high-quality rendering across different devices, provide assets for various scales/DPIs using the naming conventions or directory structures supported by the target platforms.
  7. Use CSharpMath.Avalonia for Avalonia UI

    master

    To display math in Avalonia, use the MathView control. You can define it in XAML or via C# code.

    XAML Usage:

    <math:MathView LaTeX="x + 2 \sqrt{x} + 1 = (\sqrt x+1)^2" />

    C# Usage:

    var view = new CSharpMath.Avalonia.MathView();
    view.LaTeX = @"\frac\sqrt23";
    somePanel.Children.Add(view);
    <UserControl xmlns="https://github.com/avaloniaui"
                 xmlns:math="clr-namespace:CSharpMath.Avalonia;assembly=CSharpMath.Avalonia"
                 x:Class="Namespace.Class">
        <math:MathView LaTeX="x + 2 \sqrt{x} + 1 = (\sqrt x+1)^2" />
    </UserControl>
  8. Edit and evaluate math expressions

    master

    You can process key presses to generate math structures or LaTeX strings using CSharpMath.Rendering.FrontEnd.MathKeyboard. Once you have a CSharpMath.Atom.MathList, you can use CSharpMath.Evaluation.Evaluate to perform mathematical analysis or CSharpMath.Evaluation.Interpret for a more convenient experience that handles errors as red text and automatically switches between simplifying expressions and solving equations.

    Note: CSharpMath.Evaluation is part of the 0.5.0 update and may require using the nightly feed if not yet released in the stable version.

    // Manual evaluation approach
    var keyboard = new CSharpMath.Rendering.FrontEnd.MathKeyboard();
    keyboard.KeyPress(CSharpMath.Editor.MathKeyboardInput.Sine, CSharpMath.Editor.MathKeyboardInput.SmallTheta);
    var (math, error) = CSharpMath.Evaluation.Evaluate(keyboard.MathList);
    
    if (error != null) 
    {
        // Handle invalid input via error string
    }
    else
    {
        switch (math)
        {
            case CSharpMath.Evaluation.MathItem.Entity { Content: var entity }:
                // entity is an AngouriMath.Entity
                var simplifiedEntity = entity.Simplify();
                break;
            case CSharpMath.Evaluation.MathItem.Comma comma:
                // comma is a System.Collections.Generic.IEnumerable<CSharpMath.Evaluation.MathItem>
                break;
            case CSharpMath.Evaluation.MathItem.Set { Content: var set }:
                // set is an AngouriMath.Core.Set
                break;
        }
    }
    
    // Convenient interpretation approach
    var keyboard = new CSharpMath.Rendering.FrontEnd.MathKeyboard();
    keyboard.KeyPress(CSharpMath.Editor.MathKeyboardInput.Sine, CSharpMath.Editor.MathKeyboardInput.SmallTheta);
    // Automatically chooses between simplifying and solving; displays errors in red
    var resultLaTeX = CSharpMath.Evaluation.Interpret(keyboard.MathList);
  9. Use CSharpMath.Forms for Xamarin.Forms

    master

    To display math in Xamarin.Forms, use the MathView control. You can define it in XAML or via C# code.

    XAML Usage:

    <math:MathView x:Name="View" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        \frac\sqrt23
    </math:MathView>

    C# Usage:

    var view = new CSharpMath.Forms.MathView();
    view.HorizontalOptions = view.VerticalOptions = LayoutOptions.FillAndExpand;
    view.LaTeX = @"\frac\sqrt23";
    someLayout.Children.Add(view);
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:math="clr-namespace:CSharpMath.Forms;assembly=CSharpMath.Forms"
                 x:Class="Namespace.Class">
        <math:MathView x:Name="View" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            \frac\sqrt23
        </math:MathView>
    </ContentPage>
  10. Use CSharpMath.SkiaSharp for low-level rendering

    master

    Use MathPainter from the CSharpMath.SkiaSharp namespace to render LaTeX directly onto a SkiaSharp canvas. This is the underlying engine used by the Forms and Avalonia implementations.

    var painter = CSharpMath.SkiaSharp.MathPainter();
    painter.LaTeX = @"\frac\sqrt23";
    painter.Draw(someCanvas);
  11. Configure Static Web App routing and fallback for CSharpMath Uno WebAssembly

    master

    When deploying a CSharpMath Uno WebAssembly application to Azure Static Web Apps, use staticwebapp.config.json to manage client-side routing and caching behavior.

    To support Single Page Application (SPA) routing, configure navigationFallback to rewrite requests to /index.html. Ensure you exclude static assets like .css, .js, .wasm, and other binary or data files to prevent the fallback from intercepting direct asset requests.

    Caching Routes

    You can define specific routes to optimize performance:

    • Packages: Use the route /package_* to apply long-term caching (public, immutable, max-age=31536000) to package assets.
    • Fonts: Use the route /*.ttf to apply long-term caching to TrueType font files.
    • Default: Use the wildcard route /* to apply a shorter revalidation period (must-revalidate, max-age=3600) for all other content.
    {
      "navigationFallback": {
        "rewrite": "/index.html",
        "exclude": [
          "*.{css,js}",
          "*.{png}",
          "*.{c,h,wasm,clr,pdb,dat,txt}"
        ]
      },
      "routes": [
        {
          "route": "/package_*",
          "headers": {
            "cache-control": "public, immutable, max-age=31536000"
          }
        },
        {
          "route": "/*.ttf",
          "headers": {
            "cache-control": "public, immutable, max-age=31536000"
          }
        },
        {
          "route": "/*",
          "headers": {
            "cache-control": "must-revalidate, max-age=3600"
          }
        }
      ]
    }
  12. Asset scaling conventions for WinUI, iOS, and Android

    master

    When providing assets for different screen densities in Uno Platform, use the following mapping for scales and platform-specific identifiers:

    ScaleWinUIiOSAndroid
    100scale-100@1xmdpi
    125scale-125N/AN/A
    150scale-150N/Ahdpi
    200scale-200@2xxhdpi
    300scale-300@3xxxxhdpi
    400scale-400N/Axxxhdpi

    Example file structures:

    Suffix-based (WinUI style):

    \Assets\Images\logo.scale-100.png
    \Assets\Images\logo.scale-200.png
    \Assets\Images\logo.scale-400.png

    Directory-based (iOS/Android style):

    \Assets\Images\scale-100\logo.png
    \Assets\Images\scale-200\logo.png
    \Assets\Images\scale-400\logo.png