Capturing Your iOS App in Animated GIF Glory

LICEcap Capture at 30fps

Showing the coolness of your iOS app in a web format can be very difficult, depending on what about your app makes it shine. If your app thrives on animation, especially the new UIKit Dynamics fun, you will need more than one frame to portray what your app does: enter the animated GIF, mother of all awesomeness.

Here is the method I used to make the images for my Xamarin UIGravityBehavior recipe. That said, if you know a better way to do this, toss a comment out there; I’d love to hear about it.

While I use these methods for my Xamarin.iOS creations, they apply equally to native apps and most anything running on a Mac.

The Tool: LICEcap

While the name sounds slightly…off, it definitely gets the job done. LICEcap, from Cockos Incorporated, is a quick disk image install. In fact, here’s LICEcap’s capture of me installing LICEcap.

Installing LICEcap

One thing to notice, these GIFs are not a great way to capture complex color palettes like the gradients in the install image folder. There may be a tool that is better at that, but you will probably compromise file size for fidelity. That install GIF was 81kb.

Capturing the iOS Simulator

With LICEcap, you capture an arbitrary portion of the screen, so you can capture just a portion of your app all the way to the full simulator with your Twitter feed rolling in the background around it. LICEcap loads as a transparent window, looking eerily as if something failed to render. Instead, what the program frames is what will be captured. You pull the various window edges and corners as needed to frame your target. It can be maddening to adjust it just right if you are shooting for specific pixels. You can also set exact pixel measurements with the two bottom inputs.

Using LICEcap to capture an animated GIF

After you set your capture area, you can set a maximum frames per second (FPS) as well. For representative purposes, it seemed I needed fewer FPS than I thought. The resulting file size variation from FPS settings will depend heavily on your recording length and the complexity of the graphics. For my UIGravityBehavior recipe, practically ideal for GIF compression, it wasn’t a big difference from 5fps to 30fps. For some animations, file size can get substantial fairly quickly.

LICEcap Capture at 30fps
LICEcap Capture at 5fps
FPSFile Size
5fps24kb
10fps43kb
15fps46kb
20fps66kb
25fps67kb
30fps68kb

Unless you want a huge recording, you probably want to scale the Simulator to 50% with Command+3. For a full-app capture, you will end up getting the bottom rounded corners of the window unless you crop a few pixels. For most apps, trimming those pixels doesn’t seem to be a loss. At half scale, I find setting LICEcap to 318×564 then lining up with a top corner works quite well. Doing so highlights one frustration with the program. When capturing skinny views with exact dimensions, such as the iOS Simulator in portrait, you need to enter your height first or the field disappears before you can give it a value.

Once you are all set, hit the record button. Give your file a name and a location. You will also have a few options here that may be of interest, such as showing a circle for mouse button presses or loop repeat count. When you are all set hit “Save” and you will get a 3-2-1 countdown in the title bar before recording begins. After everything is complete, simply hit “Stop” to save the result. (You can also pause and resume during a recording.)

Trimming the result

If you find you have a bunch of extra frames in your animation, open your GIF in Preview. From there you can selecting the offending frames and hit delete. But, once you edit in Preview, any infinite looping you had will be gone. I found Gifsicle, a command line utility, fixed this for me quite nicely.

gifsicle -bl ~/path/to/your/file.gif

Other Capture Methods

Still Images

If you really just need a static screenshot, don’t forget the baked-in offerings. The easiest shots can be done in the iOS Simulator, a simple Command+S (File: Save Screen Shot) will save a PNG result of your app to the desktop.

Need to capture the Simulator among other windows? You capture the full screen with Command+Shift+3 and can then crop to your desired size. To capture a partial screenshot, hit Command+Shift+4 and draw what to capture with the crosshairs. These images are also saved to your desktop, time-stamped, but they are formatted “Screen Shot {yyyy-MM-dd} at {h.mm.ss tt}”.

Capturing a Video

If you need a video to do your app justice, by all means, let me introduce you to this neat tool included on your Mac for free: QuickTime Player. Load it up and select “File”, then “New Screen Recording”. Here’s where I would embed a video of me doing that, but you can’t start a new screen recording while doing a screen recording.

Using QuickTime Player for Screen Recordings

Other Options?

Utilities such as Jing capture in a Flash-based format, but I have mixed feelings about requiring Flash, no matter how common it may be. While the animation captures I tried with it were smooth and the color gradients captured fine, the file sizes got substantial quickly.

If there is some awesome, affordable or free tool out there that you use to make capturing animations insanely easy? I’d love to hear about it.

MonoTouch Programming in Visual Studio

TL;DR

Never underestimate the little time sinks of switching between IDEs regularly. To write MonoTouch code in Visual Studio 2010 (debug/deploy still requires MonoDevelop on a Mac), go get VSMonoTouch. If you have any issues getting it going, you may need to toss in some project file tweaks.

Background

I’ve been programming with MonoTouch for a few months now using MonoDevelop. I really enjoy learning new things (even if MonoTouch saved me from learning Objective-C), but switching IDEs always tosses a few kinks in my productivity. I have tweaked a number of key bindings in MonoDevelop to match Visual Studio, some at the cost of my ability to adapt to the Mac’s defaults that are normally used everywhere. At one point I switched copy and paste to use Ctrl in MonoDevelop, but then I kept screwing up outside of the IDE. Regardless, I have become fairly productive in MonoDevelop from simply adapting to the new system through repetition (often screwing up when I switch back to Windows now).

I don’t really have a problem with MonoDevelop most days, but I definitely prefer the Windows system of maneuvering windows and working on multiple displays. Even if I were a Mac-only person, I would hate how full-screen mode works on a Mac. While I have adapted to my new MonoDevelop workflow, I definitely miss having multiple tabs open in a single project; to open multiple instances of MonoDevelop on a Mac, you even need a simple hack. Having to flip around between MonoDevelop and Chrome as I drink from the MonoTouch learning firehose only compounds the window management issue.

Nothing seems to get you around the need for a Mac when testing/debugging/deploying a MonoTouch project, but having Visual Studio as your primary IDE for all your .NET projects can definitely speed things up.

VSMonoTouch

Enter VSMonoTouch by Jonas Follesø (follesoe on GitHub).

This Visual Studio VSIX add-in (warning: requires a non-free Visual Studio) seems to create a system for allowing Visual Studio to recognize the MonoTouch framework and its project type and use the correct DLLs for compiling. For simplicity’s sake, just follow the instructions in the project README for your first run. If that doesn’t work, start looking for tweaks.

The final process I used was simply moved the VSIX install step from first to last on the instructions list from the README (with absolutely no reason to explain why it worked). Regardless, feel free to try some restarts on the off chance you have issues.

  1. Copy the MonoTouch binaries from your Mac development environment to your Visual Studio 2010 development environment. Copy all the files from /Developer/MonoTouch/usr/lib/mono/2.1/ on your Mac to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v1.0 on your PC.
  2. Add a RedistList-folder under your newly created v1.0-folder. Download the FrameworkList.xml file and add it to the RedistList-folder.
  3. Download and run the vsix-package from the github page.

Code Reference Quirks

It seems that some systems have an easier time getting VSMonoTouch to run than others. On my Windows 7 machine with Visual Studio 2010 (10.0.40219.1 SP1Rel), .NET 4.5, and various Visual Studio 2012 free components; I had a few issues getting things just right. The first three times I tried things out, I simply couldn’t get Visual Studio to acknowledge the project type. It would load the solution I have from MonoDevelop but leave the projects unloaded.

I tried all sorts of variations on the FrameworkList.xml file and gave up for a while.

mscorlib

Today, I decided to try again after I noticed a few updates to a project issue with mscorlib. That wasn’t the issue I was having, but I was hoping anyone trying to solve this issue may accidentally find a solution to help my problem. Oddly, after installing the DLLs first and then the VSIX, it all started loading correctly but with some compile errors and warnings.

  • Error: “An assembly with the same identity ‘mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ has already been imported. Try removing one of the duplicate references.”
  • Warning: “No way to resolve conflict between “mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” and “mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”. Choosing “mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ arbitrarily.”
  • Warning: “There was a mismatch between the processor architecture of the project being built “MSIL” and the processor architecture of the reference “C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll”, “x86″. This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.”
  • Warning: “Found conflicts between different versions of the same dependent assembly.”

This is where that [mscorlib project issue] came into play. There was a note on the VSMonoTouch README about making sure to have explicit mscorlib references, but I already did. Checking the box on the “Do not reference mscorlib.dll” project property, though, removed those errors.

VSMonoTouch mscorlib.dll issue fix

If you are a fan of tweaking csproj XML directly instead of through the project properties editor, feel free to add this node to any compilation PropertyGroups manually.

<NoStdLib>true</NoStdLib>

System.Web.Services

After fixing the mscorlib.dll issues, though, I got a new error popping up. This final compile error was coming from code I wrote, so that was a good sign (I guess).

  • Error: “The name ‘HttpUtility’ does not exist in the current context”

Since I am writing an application that interfaces almost entirely with the web-based JSON API I wrote, there are a few places where I am sending back user content to that system. The URL encoding I use simply hits HttpUtility.UrlEncode. In MonoTouch, you need to make sure you reference System.Web.Services to get UrlEncode. But, in Visual Studio Land, the .NET 4.0+ DLL doesn’t have such a method. You can fix this issue with a static version reference on that DLL. There may be a version-agnostic way to do this, but I ended up editing my csproj file to point to the specific version found in the MonoTouch DLLs.

<Reference Include="System.Web.Services, Version=2.0.5.0" />

I will probably have to update this manually whenever a new version hits MonoTouch, but I definitely can live with that.

VSMonoTouch In Use

After getting the loading and compile errors worked out, I now have a MonoTouch solution building successfully in Visual Studio 2010. It contains a core project shared with the Sierra Trading Post Android app (using a few compiler directives) and my MonoTouch project containing almost entirely UI-related code. I write some code and it tells me whether it will compile correctly against the MonoTouch DLLs. I haven’t tried abusing the reliability of this system with any features that are not part of Mono (e.g., async/await) or MonoTouch (e.g., dynamic) yet.

Since my project is currently synced through Dropbox, I just save what I have on Windows and roll on over to the MacBook to run things on the simulator or deploy them to a physical device and/or TestFlight (which is far better than sliced bread, at least for getting your app out to multiple devices). MonoDevelop will even automatically update your project files if you already have it open, though I don’t recommend editing on both systems simultaneously without having something between them to handle conflicts that are bound to arise.

Creating an animated spinner in a Xamarin.iOS (MonoTouch) UIImageView

Background

I’m well into my first week of building the Sierra Trading Post first iOS app using Xamarin.iOS and it has been a fun ride so far. One of the first things needed was a system for showing a loading image while asynchronously retrieving the final image with a web request.

Attempt 1

Xamarin has a recipe for using a UIImageView‘s AnimationImages to make a spinner.

UIImageView someImageView = new UIImageView();
someImageView.AnimationImages = new UIImage[] {
    UIImage.FromBundle("Spinning Circle_1.png"),
    UIImage.FromBundle("Spinning Circle_2.png"),
    UIImage.FromBundle("Spinning Circle_3.png"),
    UIImage.FromBundle("Spinning Circle_4.png"),
};
someImageView.AnimationRepeatCount = 0; // Repeat forever.
someImageView.AnimationDuration = 1.0; // Every 1s.
someImageView.StartAnimating();

It may be possible to make this work, but it wasn’t quite what I needed. This seems to be more of an image rotation than an animation. As a result, it creates a jerky animation between the various images equally distributed over the AnimationDuration you set.

After this, attempts to find some ideas for a better solution lead me to about a hundred lines of code that proved a difficult to consume, involving a CGBitmapContext and CGAffineTransform.MakRotation. (To be fair, this code isn’t doing something as simple as what I want to do.) Hoping to avoid that, I simply added four more rotation positions into the list. It would probably take many more to make it appear smooth. Any more than that and I really didn’t want to bloat my project with minute rotations of the same PNG. Back to Google I went.

Solution

After enough poking around some slightly related Google results, I began to understand enough of CABasicAnimation to see how it could work for the job. You create the desired animation and add an instance of UIImageView.Layer.

    // Image to be rotated (in this case, found in the project as "/Assets/Images/loading_icon.png").
    UIImageView someImageView = new UIImageView(UIImage.FromBundle("Assets/Images/loading_icon"));
    CABasicAnimation rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
    rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2); // full rotation (in radians)
    rotationAnimation.RepeatCount = int.MaxValue; // repeat forever
    rotationAnimation.Duration = 1;
    // Give the added animation a key for referencing it later (to remove, in this case).
    someImageView.Layer.AddAnimation(rotationAnimation, "rotationAnimation");

The main part of this is the simple rotation CABasicAnimation that is applied to a Layer of a UIImageView. In this case, it is set to do a full rotation (accepted in radians) every one second through a very large number of repetitions. The repetitions is actually one oddity in the switch to this new method. When you set UIImageView.AnimationRepeatCount, you can set it to zero to make it loop forever. Oddly, a CABasicAnimation.RepeatCount set to zero is the same as one, and it loops a single time before stopping.

Code (Example doing for a bunch of UITableView cells)

static NSString key = new NSString("somecellkey");
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) {
    UITableViewCell cell = tableView.DequeueReusableCell(key);
    if (cell == null) {
        cell = new UITableViewCell(UITableViewCellStyle.Default, key);
    }

    // Image to be rotated (in this case, found in the project as "/Assets/Images/loading_icon.png").
    cell.ImageView.Image = UIImage.FromBundle("Assets/Images/loading_icon");
    CABasicAnimation rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
    rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2); // full rotation (in radians)
    rotationAnimation.RepeatCount = int.MaxValue; // repeat forever
    rotationAnimation.Duration = 1;
    // Give the added animation a key for referencing it later (to remove, in this case).
    cell.ImageView.Layer.AddAnimation(rotationAnimation, "rotationAnimation");

    // Do your lazy-loading of the image (blog post coming soon...maybe).
    ...

    // For a good time, you can keep rotating your final, lazy-loaded image by not calling this line.
    cell.ImageView.Layer.RemoveAnimation("rotationAnimation");

    // Do the rest of your visual stuff to the cell.
    ...

    return cell;
}

More Code

If you want a quick demo application of the differences, check out the GitHub repo I put together [and finally got around to sharing]. It is a simple demo of two UIImageViews that implement the two methods here. Clicking anywhere will toggle between the two.

Here’s a quick video snippet of the demo code running.