<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[breakfastcode - Medium]]></title>
        <description><![CDATA[A mixtape of Swift programming, algorithms and UX. - Medium]]></description>
        <link>https://medium.com/breakfastcode?source=rss----ecba1f479767---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>breakfastcode - Medium</title>
            <link>https://medium.com/breakfastcode?source=rss----ecba1f479767---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:53:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/breakfastcode" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to make a $1 Unistroke Gesture Recognizer in Swift]]></title>
            <link>https://medium.com/breakfastcode/how-to-make-a-1-unistroke-gesture-recognizer-in-swift-91881e9c1d98?source=rss----ecba1f479767---4</link>
            <guid isPermaLink="false">https://medium.com/p/91881e9c1d98</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unistroke]]></category>
            <category><![CDATA[gesture-recognizer]]></category>
            <dc:creator><![CDATA[Daniele Margutti]]></dc:creator>
            <pubDate>Thu, 15 Dec 2016 19:09:34 GMT</pubDate>
            <atom:updated>2015-10-16T16:51:35.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRmH4eTnpeIPMMn7lnE2VQ.jpeg" /></figure><p>Although many modern smartphone and tablet display offers opportunities for using pen and finger in their user interfaces, implementing gesture recognition has been largely a privilege of AI/pattern matching experts, not general software programmers neither human-computer interaction designers (HCI).</p><p>There are different algorithms developed over the time which are able to recognise and translate gestures or symbols in something we can use to provide a new kind of interaction to our end users. Some of these are complex to write, some others may require a capable hardware (although modern devices maybe better than any low-end consumer PC); today I would to discuss about $1, an easy, cheap and usable almost anywhere algorithm which is able to provide from 97% to 99% of accuracy comparing to other noble ones like DTW or Rubine (depending by the number of templates provided for each symbol).<br>Moreover with medium-speed gesture, in which users balanced speed and accuracy of the drawn, gestures were better recognized than slow or fast gestures for all three recognizers.</p><blockquote><strong>Easy and cheap it provide from 97% to 99% of accuracy in less than 100 lines of code.</strong></blockquote><p>$1 Recognizer was developed by <em>Jacob O. Wobbrok</em>, <em>Andrew D. Wilson</em> and <em>Yang Li</em> and it is discussed in <a href="https://faculty.washington.edu/wobbrock/pubs/uist-07.01.pdf">this paper</a> from University of Washington (obviously, this post is heavily based on it). In this post I’ll talk about the main principles of the algorithm and I’ll propose a pure Swift implementation (future posts will include some variants which are able to support multistroke gestures).</p><p>In this article I’ll explain how to make an unistroke gesture recognizer with a sample iOS application; that’s the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP7wQVkmTkPY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP7wQVkmTkPY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP7wQVkmTkPY%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f114432f54de14c90ddcabf0058f03/href">https://medium.com/media/e8f114432f54de14c90ddcabf0058f03/href</a></iframe><p>$1 Recognizer is very simple; in fact is involving only a basic geometry and trigonometry knowledge and the length of the code is less than 100 lines. It also support configurable rotation, scale and position invariance while it does not require any training session to become usable.</p><p>There are several variants of this algorithm; soon as I can I’ll discuss another variant, called <a href="http://depts.washington.edu/aimgroup/proj/dollar/pdollar.html">$P recognizer</a>: $P can recognize gestures made with any number of strokes (while $1 is single stroke) in any order or direction with low storage cost (whereas $N, another variant, had high storage costs since it internally represented all the same variations that $P’s matching algorithm can handle seamlessly).</p><h3>The algorithm in detail</h3><p>What’s a gesture? Basically it’s a set of points (we call it candidate points or C); our scope is to find which set of previously recorded template points (we call it Ti) it’s close to our input.<br>Both candidate and template points must be recorded and sampled at a specified rate (in order to limit the number of points and so the data to manage) by some kind of sensing hardware and software (in our case we obviously use an iOS device).<br>This fact coupled with human errors mean that points in similar C and Ti will rarely “line up” so as to be easily comparable.</p><p>The example below describe two pairs of gestures, a “pigtail” and an “x” symbol which are composed by different points and with a different size; moreover the pigtail may be rotated by 90° CW degree and it will be similar to the x symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*qjpR8NfmsLZckYPvrvz7sw.png" /><figcaption><em>(From the paper)</em> Two pairs of fast (~600 ms) gestures made by a subject with a stylus. The number of points in corresponding sections are labeled. Clearly, a 1:1 comparison of points is insufficient.</figcaption></figure><p>With these constraints in mind, clearly any 1:1 comparison of the points is insufficient.<br>So $1 algorithm must be also resistant to variations of sampling operation and, moreover, should support any rotation/scale and position invariance.</p><h3>Sampling data points</h3><p>As we said above movement speed have a clear effect on the number of input points in a gesture; this is not only an issue related to our choosed sample rate, but it is also dependent from the input hardware: with a fast gesture we’ll have a minor number of sampled points than we may have with a slow gesture (see the picture below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*OYQF4n0sD5pQUwIOEIDjWQ.png" /><figcaption>In this example you can see the different number of points sampled by the hardware with a fast and a slow gesture. In order to make them comparable we need to resample our input points array.</figcaption></figure><p>So, in order to make two gesture comparable we first resample our gestures points array; for an original M points array we get a N equidistantly spaced points array; a balanced value of N is 64; it guarantees a gret result without a big loss of precisions or an huge amount of data to manage.</p><p>To resample we first calculate the total length of the M point path; dividing this length by (N-1) gives the length of each increment INC, between N points.<br>Then the path is stepped through such that when the distance covered exceeds I, a new point is added through linear interpolation.<br>At the end of this step we’ll have a N point path and we can measure the distance from our input array and any other templates array.</p><p>That’s the swift code (StrokePoint data type is similar to CGPoint but uses double in order to get max precision).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdfc3f25223c39766ba0a7d0ae96dd32/href">https://medium.com/media/fdfc3f25223c39766ba0a7d0ae96dd32/href</a></iframe><p>This is the result of a sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*dvon2VUulOXuzyRPTVxi0A.png" /></figure><h3><strong>Get the best rotation angle to align with templates</strong></h3><p>At this time we have two paths of ordered points (our input array and, for example the n-th template array); there is not any closed form solution to determine the angle to which one set points should be rotated to best align with the other one.<br>$1 recognizer than iterate over the space of possible angles to search the best alignment between two point-paths.<br>While this kind of operation maybe prohibitive for other algorithms, even naïvely rotating the gesture by 1° for 360° is fast enough even with 30 gesture templates; however the algorithm itself try to avoid this brute force approach and do some “rotation tricks” that makes the search for optional angle a faster process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*k8bnfczxNSqgPY6f8gKsoQ.png" /><figcaption><em>Rotating a triangle so that its “indicative angle” is at 0° (straight right). This approximates finding the best angular match.</em></figcaption></figure><p>The first step is to search gesture’s indicative angle, which it’s defined as the angle formed between the centroid of the gesture and the gesture’s first point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0977ba19edf38b0fa6765362636e93fb/href">https://medium.com/media/0977ba19edf38b0fa6765362636e93fb/href</a></iframe><p>Then we rotate the gesture so this angle is at 0°.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8950fbd78b3c9190515313c11faf1a7f/href">https://medium.com/media/8950fbd78b3c9190515313c11faf1a7f/href</a></iframe><h3>Scale &amp; Translate</h3><p>Our next step is to scale (non-uniformly) the gesture to a reference square: this allow the algorithm to rotate the candidate about its centroid and safely assume that changes in pairwise point-distances between the candidate and the template are due only to rotation, not to aspect ratio.<br>At the end of the scale the gesture itself is translated to put the centroid at the origin point (0,0).</p><p>That’s the code portion used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0014569e4c2182cbf7e3f2357b872a8/href">https://medium.com/media/b0014569e4c2182cbf7e3f2357b872a8/href</a></iframe><h3>Find the optimal angle and get the best score</h3><p>The final step of this algorithm compare each stored template with our input path-points.<br>This comparison is made using a path-distance function which return the distance between our two path-points; the result of this function is then converted to a score point by another function.<br>Input gesture may be rotated in order to find the best angular alignment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e92050af6b1a06d1f4d967791761c710/href">https://medium.com/media/e92050af6b1a06d1f4d967791761c710/href</a></iframe><h3>Complete project</h3><p>$1 Project in Swift is available via github at <a href="https://github.com/malcommac/SwiftUnistroke">https://github.com/malcommac/SwiftUnistroke</a>; code is compatible with Swift2 and includes a simple iOS application which is able to recognize a set of specified template points. You are free to use it in your projects (both open source and commercial ones), make your pull requests or issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91881e9c1d98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/breakfastcode/how-to-make-a-1-unistroke-gesture-recognizer-in-swift-91881e9c1d98">How to make a $1 Unistroke Gesture Recognizer in Swift</a> was originally published in <a href="https://medium.com/breakfastcode">breakfastcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attributed String in Swift: the right way]]></title>
            <link>https://medium.com/breakfastcode/attributed-strings-in-swift-6d4b37db59a5?source=rss----ecba1f479767---4</link>
            <guid isPermaLink="false">https://medium.com/p/6d4b37db59a5</guid>
            <category><![CDATA[nsattributedstring]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Daniele Margutti]]></dc:creator>
            <pubDate>Thu, 15 Dec 2016 19:08:52 GMT</pubDate>
            <atom:updated>2017-09-28T14:33:14.148Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we can make Cocoa a little less verbose and a little more type safe.</em></p><p>When I’ve started working with Cocoa in later in 2001 I was coming from some experience in Java and a little less of pure C. Cocoa was simply amazing (check out this <a href="http://arstechnica.com/apple/2012/12/the-legacy-of-next-lives-on-in-os-x/">cool old article</a> from Ars Technica) and the difference with the old <a href="https://en.wikipedia.org/wiki/Macintosh_Toolbox">Mac Toolbox</a> was huge.<br>A brave new world was coming and I was pretty exciting of all opportunities which a complete full-featured framework like that could offer to me.</p><p>Lots of years are passed since these days, the old NeXT heritage was taken from iOS with UIKit and we lived the mobile revolution also and especially thanks to a complete solution which really helped to create an fertile environment for what we call The App Economy (which, of course, was started on macOS).</p><p>With Swift it was like stepping back in time and live the same experience another time; even thanks to this new opportunity, UIKit (and to a lesser extent AppKit) is experiencing a smooth transition to a new life (while my dream is all about a new rewritten framework, I can understand the reason behind the choice of a smooth transition of the Foundation inside the <a href="https://swift.org/core-libraries/#foundation">Swift Standard Library</a>).<br>So, while we’re still fighting with this transition we can make our life easier anyway.</p><p>NSAttributedString is one of the things I’ve started to hate in a post-Swift world; creating, combining and applying styles to a string, then render it it’s not a difficult task, but it’s boring, verbose and so damn inelegant.<br>It’s like playing withAuto Layout via code until not so long ago; we can deserve a better experience, especially now we are using Swift: we can make it type-safe, easy and coincise to use.</p><p>So, starting from this experience I’ve created a small library, called SwiftRichString (an original name, don’t you think so?).</p><h4>Type Safety</h4><p>The first issue I wanted to solve is regards type-safe; <a href="http://www.dummies.com/programming/macintosh/type-safety-in-swift/">Swift implements <em>type safety</em></a><em>,</em> which basically means that you can’t use a variable inappropriately for the terms of its type; letting the development environment enforce type safety is the safest way of handling these problems.<br>NSAttributedStrings uses NSDictionary to set attributes for text; attributes identifiers (as strings) are passed along with their values.<br>Like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/768ac3280bcff5cc6718b63742b00989/href">https://medium.com/media/768ac3280bcff5cc6718b63742b00989/href</a></iframe><p>In order to make it safer I’ve introduced the concept of Style. You can create a Style with a name (we will discuss about it later) and assign attributes using a traditional creational pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05aed4e74250e48f18bcca58e01016fa/href">https://medium.com/media/05aed4e74250e48f18bcca58e01016fa/href</a></iframe><p>Even font attribute is type safe; you can create a UIFont object in a type-safe manner by specifing one of the fonts which iOS made available. FontAttribute can also be extended and you can add your own font names (or if you are lazy you can instantiate a font in an old fashion way by specifing a literal). By looking inside the library you will found some other special structures like StrikeAttribute, ShadowAttribute or UnderlineAttribute; all of them are used to make things cleaner and faster to use (<a href="https://github.com/malcommac/SwiftRichString#attributes">take a look at the doc</a> for a complete list).</p><p>The ideal scenario for Style is to create a set of styles you will use along your code of your next application.</p><p>There is only one special Style which is called .default. Default style is applied in first place regardeless the order in which it’s passed to styles parameter of a functions. This ensure you can have a base common style for your string and add one or more attributes over it easily.</p><p>If you don’t need to use tagged string in your code you can create Style objects without giving to them a name; simply use it inside set() functions.</p><h4>Painless attributed string creation and management</h4><p>Creating NSAttributedString, combine them and apply style is tedious and verbose; tons of boring code to make a pretty easy task.<br>Let me show to you a very simple example.</p><p><strong>Article continues on my block.</strong><br><a href="http://danielemargutti.com/2016/12/04/attributed-string-in-swift-the-right-way/"><strong>Click here to continue reading!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d4b37db59a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/breakfastcode/attributed-strings-in-swift-6d4b37db59a5">Attributed String in Swift: the right way</a> was originally published in <a href="https://medium.com/breakfastcode">breakfastcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>