Beautiful math equation rendering on iOS and MacOS

Related tags

Math iosMath
Overview

iosMath

Build Status Version License Platform

iosMath is a library for displaying beautifully rendered math equations in iOS and MacOS applications. It typesets formulae written using the LaTeX in a UILabel equivalent class. It uses the same typesetting rules as LaTeX and so the equations are rendered exactly as LaTeX would render them.

It is similar to MathJax or KaTeX for the web but for native iOS or MacOS applications without having to use a UIWebView and Javascript. More importantly, it is significantly faster than using a UIWebView.

Examples

Here are screenshots of some formulae that you could render with this library:

Quadratic Formula

Calculus

AM-GM

Ramanujan Identity

The EXAMPLES.md file contains more examples.

Requirements

iosMath works on iOS 6+ or MacOS 10.8+ and requires ARC to build. It depends on the following Apple frameworks:

  • Foundation.framework
  • CoreGraphics.framework
  • QuartzCore.framework
  • CoreText.framework

Additionally for iOS it requires:

  • UIKit.framework

Additionally for MacOS it requires:

  • AppKit.framework

Installation

Cocoapods

iosMath is available through CocoaPods. To install it:

  1. Add a entry for iosMath to your Podfile: pod 'iosMath'.
  2. Install the pod by running pod install.

Static library

You can also add iosMath as a static library to your project or workspace.

  1. Download the latest code version or add the repository as a git submodule to your git-tracked project.
  2. Open your project in Xcode, then drag and drop iosMath.xcodeproj onto your project or workspace (use the "Product Navigator view").
  3. Select your target and go to the Build phases tab. In the Link Binary With Libraries section select the add button. On the sheet find and add libIosMath.a. You might also need to add iosMath to the Target Dependencies list.
  4. Add the MathFontBundle to the list of Copy Bundle Resources.
  5. Include IosMath wherever you need it with #import <IosMath/IosMath.h>.

Usage

The library provides a class MTMathUILabel which is a UIView that supports rendering math equations. To display an equation simply create an MTMathUILabel as follows:

#import "MTMathUILabel.h"

MTMathUILabel* label = [[MTMathUILabel alloc] init];
label.latex = @"x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}";

Adding MTMathUILabel as a sub-view of your UIView as will render the quadratic formula example shown above.

Included Features

This is a list of formula types that the library currently supports:

  • Simple algebraic equations
  • Fractions and continued fractions
  • Exponents and subscripts
  • Trigonometric formulae
  • Square roots and n-th roots
  • Calculus symbos - limits, derivatives, integrals
  • Big operators (e.g. product, sum)
  • Big delimiters (using \left and \right)
  • Greek alphabet
  • Combinatorics (\binom, \choose etc.)
  • Geometry symbols (e.g. angle, congruence etc.)
  • Ratios, proportions, percents
  • Math spacing
  • Overline and underline
  • Math accents
  • Matrices
  • Equation alignment
  • Change bold, roman, caligraphic and other font styles (\bf, \text, etc.)
  • Most commonly used math symbols
  • Colors

Example

There is a sample app included in this project that shows how to use the app and the different equations that you can render. To run the sample app, clone the repository, and run pod install first. Then on iOS run the iosMathExample app. For MacOS run the MacOSMath app.

Advanced configuration

MTMathUILabel supports some advanced configuration options:

Math mode

You can change the mode of the MTMathUILabel between Display Mode (equivalent to $$ or \[ in LaTeX) and Text Mode (equivalent to $ or \( in LaTeX). The default style is Display. To switch to Text simply:

label.labelMode = kMTMathUILabelModeText;
Text Alignment

The default alignment of the equations is left. This can be changed to center or right as follows:

label.textAlignment = kMTTextAlignmentCenter;
Font size

The default font-size is 20pt. You can change it as follows:

label.fontSize = 30;
Font

The default font is Latin Modern Math. This can be changed as:

label.font = [[MTFontManager fontManager] termesFontWithSize:20];

This project has 3 fonts bundled with it, but you can use any OTF math font.

Color

The default color of the rendered equation is black. You can change it to any other color as follows:

label.textColor = [UIColor redColor];

It is also possible to set different colors for different parts of the equation. Just access the displayList field and set the textColor on the underlying displays that you want to change the color of.

Custom Commands

You can define your own commands that are not already predefined. This is similar to macros is LaTeX. To define your own command use:

[MTMathAtomFactory addLatexSymbol:@"lcm"
                            value:[MTMathAtomFactory operatorWithName:@"lcm" limits:NO]];

This creates a \lcm command that can be used in the LaTeX.

Content Insets

The MTMathUILabel has contentInsets for finer control of placement of the equation in relation to the view.

If you need to set it you can do as follows:

label.contentInsets = UIEdgeInsetsMake(0, 10, 0, 20);
Error handling

If the LaTeX text given to MTMathUILabel is invalid or if it contains commands that aren't currently supported then an error message will be displayed instead of the label.

This error can be programmatically retrieved as label.error. If you prefer not to display anything then set:

label.displayErrorInline = NO;

Future Enhancements

Note this is not a complete implementation of LaTeX math mode. There are some important pieces that are missing and will be included in future updates. This includes:

  • Support for explicit big delimiters (bigl, bigr etc.)
  • Addition of missing plain TeX commands

Related Projects

For people looking for things beyond just rendering math, there are two related projects:

  • MathEditor: A WYSIWYG editor for math equations on iOS.
  • MathSolver: A library for solving math equations.

License

iosMath is available under the MIT license. See the LICENSE file for more info.

Fonts

This distribution contains the following fonts. These fonts are licensed as follows:

Comments
  • Issues with examples

    Issues with examples

    I kept getting these errors when I tried to run the examples

    ld: warning: directory not found for option '-L/Users/Scar/Library/Developer/Xcode/DerivedData/iosMath-gzlkkectzxjnvzcxyyekxvptrvhd/Build/Products/Debug-iphonesimulator/iosMath-iOS9.0'
    ld: library not found for -liosMath-iOS9.0
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    

    Could you help me see what mistake I have made?

    opened by HeroSizy 12
  • lcm  gcd  show  with errors

    lcm gcd show with errors

    for example gcd(3,5) it shows gcd35 because latex fomat is gcd{3}{5} but in your style is gcd(3,5), should recorrect it ? maybe it is my fault...

    opened by wpstarnice 10
  • Chinese characters support added.

    Chinese characters support added.

    I added some Chinese character support, and edited README file with new features. XITS Math font with Chinese characters extension is enclosed and required to display Chinese. Note that this support is not full support, only regular used Chinese fonts (both simplified and traditional, 20902 in total). The fonts are added to Unicode CJK region (range 0x4E00 - 0x9FFF, inclusive).

    Thank you for your great work!

    opened by AnZhg 9
  • MTMathListIndex pointing to innerList in MTInner

    MTMathListIndex pointing to innerList in MTInner

    I might be doing things wrong here, but I want to render an equation like,

    \left| \frac{1}{2} \right|
    

    I'm using the atoms directly rather than LaTeX strings,

    MTInner* abs = [[MTInner alloc] init];
    abs.leftBoundary = [MTMathAtom atomWithType:kMTMathAtomBoundary value:@"|"];
    abs.rightBoundary = [MTMathAtom atomWithType:kMTMathAtomBoundary value:@"|"];
    
    MTMathAtom* placeholder = [MTMathAtom atomWithType:kMTMathAtomPlaceholder value:MTSymbolWhiteSquare];
    abs.innerList = [MTMathList mathListWithAtomsArray:@[placeholder]];
    

    How do I get a MTMathAtomIndex to within the inner math list?

    opened by jacobp100 7
  • How can i implement the library with TextKit?

    How can i implement the library with TextKit?

    Hi, Thank you for sharing such a nice library with us. It is the best library I have found. Since I am very new to Xcode, can you tell me can this library integrate with the Textkit and how?

    opened by wingsiu 7
  • Fixes a check for generating a large op with with scripts under and o…

    Fixes a check for generating a large op with with scripts under and o…

    …ver when in fractions and other displays not in the main level

    @kostub This seems to work fine with all the generated math in the example app. The use case is to have the following:

    Screen Shot 2019-08-28 at 8 44 17 PM

    instead of this:

    Screen Shot 2019-08-28 at 8 46 03 PM
    opened by cupojoe 6
  • Feature: Color

    Feature: Color

    Overview:

    • [x] Support for color command
    • [x] Add Example to the iosMathExample-App
    • [ ] Write Tests

    Example: a\color{#cccccc}{b}c

    Note: The color command is used in Latex in a different way (compare \textcolor<->\color), but this implementation has the same behavior like Katex.

    opened by msaehn 6
  • Add support for Mac. More cleaner version.

    Add support for Mac. More cleaner version.

    Changes are updated due to PR #30 . Sorry I have to delete the previous branch (It was polluted by Chinese support, but I intended not to include) and start over.

    Two new categories are added.

    opened by AnZhg 6
  • Changing color of big parenthesis (ex. \\right( or \\left) ) doesn't work

    Changing color of big parenthesis (ex. \\right( or \\left) ) doesn't work

    Hello,

    First off, this library is awesome!

    For the issue, not sure if I'm doing something wrong, but if I pass \left(\color{#B0B0B0}\right) The right parenthesis remains black. I ran it through latex itself, and it runs as expected.

    Please Help!

    opened by rmehta33 5
  • How can I display symbol $

    How can I display symbol $

    Mary persuaded n friends to donate $500 each to her election campaign, and then each of these n friends persuaded n more people to donate $500 each to Mary’s campaign. If no one donated more than once and if there were no other donations, what was the value of n?

    The sentence has contain symbol $,how can I display symbol $? I try use symbol "\$" replace "$",but it not work,when it display,the symbol $ was lose.

    bug 
    opened by abuzzworld 5
  • Swift and Obj-C Discrepancy?

    Swift and Obj-C Discrepancy?

    I'm working on an iOS app in Swift 3 and I'd like to get the MTMathUILabel and MTEditableMathLabel (from MathEditor) to display Matrices. I tried following the EXAMPLES.md file and even your example ViewController.m. When I set label.latex to be a "\begin{pmatrix} a & b\\ c & d \end{pmatrix}", I always just get "invalid command begin" on my label.

    Since it works well in your example app, I'm wondering if this is caused by the fact I'm programming in swift. If not, looking for any advice to make this work. Thank you!

    opened by yuentung19 4
  • Fix memory leak in MTFont

    Fix memory leak in MTFont

    MTFont doesn't handle memory management correctly for CTFontRef and CGFontRef. The ownership policy for Core Foundation as following:

    Foundation:

    • If you create an object (either directly or by making a copy of another object—see The Create Rule), you own it.
    • If you get an object from somewhere else, you do not own it. If you want to prevent it being disposed of, you must add yourself as an owner (using CFRetain).
    • If you are an owner of an object, you must relinquish ownership when you have finished using it (using CFRelease).

    The Create Rule:

    Core Foundation functions have names that indicate when you own a returned object:

    • Object-creation functions that have “Create” embedded in the name
    • Object-duplication functions that have “Copy” embedded in the name

    Per the above policy, MTFont shouldn't call CFRetain after CTFontCreateWithGraphicsFont or CGFontCreateWithDataProvider since CFRetain is already invoked when creating the objects.

    opened by maitbayev 1
  • Add support for Swift Package Manager

    Add support for Swift Package Manager

    Almost all tests from iosMathTests pass with swift test command, except there are some numerical differences in MTTypesetterTest, probably coming from iOS/MacOS platform changes and unrelated to SPM.

    The following things were added to satisfy the Swift Package Manager requirements:

    1. Adds include folder under iosMath with symlinked headers. SPM will automatically create module.modulemap from these headers for interoperability with Swift and Objective-C @import.
    2. Symlinks fonts folder under iosMath so that the folder is packaged into a module bundle. Pointing to ../fonts in Package.swift didn't work. Maybe it is cleaner to just move the fonts folder instead of symlinking?
    3. Use the SWIFTPM_MODULE_BUNDLE preprocessor to access the module bundle. See: https://github.com/apple/swift-evolution/blob/master/proposals/0271-package-manager-resources.md
    opened by maitbayev 1
  • Can't Install via pods

    Can't Install via pods

    I try the pod install command and get the following:

     % pod install                                   
    zsh: /usr/local/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby: no such file or directory
    

    I've tried reinstalling ruby, etc. with no success. This is on macOS 11.6.2.

    Please give us a Package version!

    opened by mgriebling 0
  • Is it possible to define simple macros like \def\Ve{\;\Mbf{e}}

    Is it possible to define simple macros like \def\Ve{\;\Mbf{e}}

    I have a large amount of LaTeX files which I want to use in an iOS app. These files contain a lot of simple abbrivations like \def\Ve{;\Mbf{e}} for unit vector e which is printed in bold letters and has some leading space. Is it possible to define those simple macros?

    opened by HeinzMattes 0
  • Won't this code cause retain cycle?

    Won't this code cause retain cycle?

    Inside MTFont.m file:

    self.mathTable = [[MTFontMathTable alloc] initWithFont:self mathTable:_rawMathTable]
    

    MTFont holds MTFontMathTable, while at the same time MTFont holds MTFontMathTable

    opened by PetrGuan 0
Owner
Kostub Deshmukh
Kostub Deshmukh
Multi-dimensional Swift math

Upsurge Upsurge implements multi-dimensional data structures and operations. It brings numpy-like operations to Swift. Upsurge no longer supports DSP

Alejandro Isaza 180 Dec 20, 2022
Math expression parser built with Point•Free's swift-parsing package

swift-math-parser Basic math expression parser built with Point•Free's swift-parsing package. NOTE: currently, this uses a fork of that fixes a parsin

Brad Howes 36 Dec 14, 2022
Oovium's math engine

OoviumEngine The function parser and math engine of the iOS / macOS app Oovium, including a command line version: oov. Swift Package Manager It is pos

Joe Charlier 0 Aug 24, 2022
VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions

Purpose VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based g

Nick Lockwood 341 Dec 31, 2022
A set of protocols for Arithmetic, Statistics and Logical operations

Arithmosophi - Arithmosoϕ Arithmosophi is a set of missing protocols that simplify arithmetic and statistics on generic objects or functions. As Equat

Eric Marchand 66 Jul 9, 2022
Overload +-*/ operator for Swift, make it easier to use (and not so strict)

Easy-Cal-Swift Overview This file is an overloading of +-*/ operator for Swift, to make it easier to use (and not so strict) It can make your life wit

Wei Wang 272 Jun 29, 2022
Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

Matft Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy. Matft Feature & Usage Declaration MfArray MfType Subscription

null 80 Dec 21, 2022
Metron is a comprehensive collection of geometric functions and types that extend the 2D geometric primitives

Metron Geometry, simplified. Metron is a comprehensive collection of geometric functions and types that extend the 2D geometric primitives provided by

Toine Heuvelmans 1k Dec 5, 2022
App for LaTeX quick reference and light equation editor

LaTeX Draft I miss the LaTeX Help app, which is too ancient to work under the latest iOS unfortunately. So I will write one in hommage to LaTeX Help a

mizu-bai 1 Mar 9, 2022
Quadratic Equation Solver CLI

Quadratic Equation Solver This is lab 1 for Software Development Methodologies and Technologies This tiny CLI program written in Swift lets you solve

Dmytro Pashchenko 0 Feb 11, 2022
SwiftMath is a Swift framework providing some useful math constructs and functions

SwiftMath is a Swift framework providing some useful math constructs and functions, like complex numbers, vectors, matrices, quaternions, and polynomials.

Matteo Battaglio 175 Dec 2, 2022
iOS_Math_Practicing is a math practicing game in iOS.

iOS_Math_Practicing iOS_Math_Practicing is a math practicing game in iOS. Important! You can use the codes to do what ever you want, instead of using

Phil Chang 1 Oct 13, 2021
Multi-dimensional Swift math

Upsurge Upsurge implements multi-dimensional data structures and operations. It brings numpy-like operations to Swift. Upsurge no longer supports DSP

Alejandro Isaza 180 Dec 20, 2022
UITextField character counter with lovable UX 💖. No math skills required 🙃.

TextFieldCounter UITextField character counter with lovable UX ??. No math skills required ??. Features Set max length of UITextField. A beautiful an

Fabricio Serralvo 434 Dec 22, 2022
Math expression parser built with Point•Free's swift-parsing package

swift-math-parser Basic math expression parser built with Point•Free's swift-parsing package. NOTE: currently, this uses a fork of that fixes a parsin

Brad Howes 36 Dec 14, 2022
It is a simple maths quiz app that will help users to test their math skills.

MathQuiz It is a simple maths quiz app that will help users to test their math skills. It has the following screens 1.Welcome screen with start button

null 0 Dec 27, 2021
Oovium's math engine

OoviumEngine The function parser and math engine of the iOS / macOS app Oovium, including a command line version: oov. Swift Package Manager It is pos

Joe Charlier 0 Aug 24, 2022
Markdown parsing and rendering for iOS and OS X

CocoaMarkdown Markdown parsing and rendering for iOS and macOS CocoaMarkdown is a cross-platform framework for parsing and rendering Markdown, built o

Indragie Karunaratne 1.2k Dec 12, 2022
iOS utility classes for asynchronous rendering and display.

YYAsyncLayer iOS utility classes for asynchronous rendering and display. (It was used by YYText) Simple Usage @interface YYLabel : UIView @property NS

null 672 Dec 27, 2022
Display and interact with SVG Images on iOS / OS X, using native rendering (CoreAnimation)

SVGKit SVGKit is a Cocoa framework for rendering SVG files natively: it's fast and powerful. Some additional info and links are on the wiki Versions:

null 4.3k Jan 3, 2023