November 20th, 2014

Real-Time Code Iteration with Sketches

Sketches are a powerful new feature that we announced as a preview release at Xamarin Evolve in October. With Sketches, developers can iterate on code within Xamarin Studio and immediately see the results, without having to go through a full build and deploy cycle.

Sketches

A sketch is a file that stands alone or can be contained in a project, making it easy to move experimental code from a sketch into a code base. In some ways, it’s the immediate window on steroids.

For example, say you want to inspect the result of some code such as :

var x = 1;
var y = 2;
var z = x + y;

Sketches use a REPL (read–eval–print loop) that evaluates the code and displays the results:

sketch results

Viewing Output

There are visualizers for the output built in, too. For instance, a color is displayed as shown below:

color visualizer

You can even pin the results to the output area:

color output

Additionally, the output can display graphs of data:

output graph

Visualizing Images

The visualizer can display other types of data, too, such as images:

image visualization

Graphics Code

Having image support is nice, because it allows you to write arbitrary graphics code in a sketch and render it to an image. For example, here’s a code snippet from a blog post I wrote a while back, showing the rendering of some Core Graphics drawing code (updated for the unified API) in an iOS sketch:

// Sketch your next great idea!

using UIKit;
using Foundation;
using CoreGraphics;
//
UIGraphics.BeginImageContext (new CGSize (320.0f, 300.0f));
using (var gctx = UIGraphics.GetCurrentContext ()){

  gctx.SetLineWidth(4);
  UIColor.Purple.SetFill ();
  UIColor.Black.SetStroke ();

  var path = new CGPath ();
  path.AddLines(new CGPoint[]{
    new CGPoint(100,200),
    new CGPoint(160,100),
    new CGPoint(220,200)});
  path.CloseSubpath();

  gctx.AddPath(path);
  gctx.DrawPath(CGPathDrawingMode.FillStroke);
}

var image = UIGraphics.GetImageFromCurrentImageContext ();

UIGraphics.EndImageContext ();

This renders a triangle in the sketch, as shown below:

Core Graphics sketch

Visualizing Views

Visualizers aren’t limited to just images. You can display views as well, such as a UIView on iOS or an NSView on OS X. For example, here is an NSBox with a border:

view visualization

Where sketches start getting even more compelling is when you start using them to modify code running in the iOS simulator and the Xamarin Android Player. For example, here is some Xamarin.Forms code created on the fly in a sketch, running in the Android Player:

forms sketch

To learn more about Sketches, check out the documentation in our developer center and the Sketches’ samples. Also see Aaron Bockover‘s great talk from Evolve.

0 comments

Discussion are closed.