June 26, 2014

Lights, Camera, Action – 3D in iOS 8 with Scene Kit

By

Scene Kit is a powerful 3D graphics API that makes working with 3D a snap. It was first introduced in OS X 10.8, and has now come to iOS 8. With Scene Kit creating immersive 3D visualizations and casual 3D games no longer requires expertise in OpenGL. Building on common scene graph concepts, Scene Kit abstracts away the complexities of OpenGL and OpenGL ES, making it very easy to add 3D content to an application. However, if you are an OpenGL expert, Scene Kit has great support for tying in directly with OpenGL as well. It also includes numerous features that complement 3D graphics, such as physics, and integrates very well with several other Apple frameworks, such as Core Animation, Core Image and Sprite Kit.

3D earth

Scene Kit is extremely easy to work with. It is a declarative API that takes care of rendering. You simply set up a scene, add properties to it, and the magic of Scene Kit brings it all to life.

To work with Scene Kit you create a scene graph using the SCNScene class. A scene contains a hierarchy of nodes, represented by instances of SCNNode, defining locations in 3D space. Each node has properties such as geometry, lighting and materials that affect its appearance.

node tree

To make a scene appear on screen, you add it to an SCNView by assigning it to the view’s Scene property. Additionally, if you make any changes to the scene, SCNView will update itself to display the changes.

scene = SCNScene.Create ();
sceneView = new SCNView (View.Frame);
sceneView.Scene = scene;

Scenes can be populated from files exported via a 3d modeling tool, or programmatically from geometric primitives. For example, this is how to create a sphere and add it to the scene:

sphere = SCNSphere.Create (10.0f);
sphereNode = SCNNode.FromGeometry (sphere);
sphereNode.Position = new SCNVector3 (0, 0, 0);
scene.RootNode.AddChildNode (sphereNode);

Let There Be Light

At this point the sphere won’t display anything because there is no light in the scene. Lights in Scene Kit are created by attaching SCNLight instances to nodes. There are several types of lights ranging from various forms of directional lighting to ambient lighting. For example the following code creates an omni directional light on the side of the sphere.

// omni-directional light
var light = SCNLight.Create ();
var lightNode = SCNNode.Create ();
light.LightType = SCNLightType.Omni;
light.Color = UIColor.Blue;
lightNode.Light = light;
lightNode.Position = new SCNVector3 (-40, 40, 60);
scene.RootNode.AddChildNode (lightNode);

Omni directional lighting produces a diffuse reflection resulting in an even lighting, sort of like shining a flashlight. Creating ambient light is similar, although it has no direction as it shines equally in all directions. Think of it like mood lighting :)

// ambient light
ambientLight = SCNLight.Create ();
ambientLightNode = SCNNode.Create ();
ambientLight.LightType = SCNLightType.Ambient;
ambientLight.Color = UIColor.Purple;
ambientLightNode.Light = ambientLight;
scene.RootNode.AddChildNode (ambientLightNode);

With the lights in place, the sphere is now visible in the scene.

sphere

Adding a Camera

Adding a camera (SCNCamera) to the scene changes the point of view. The pattern to add the camera is similar. Create the camera, attach it to a node and add the node to the scene.

// camera
camera = new SCNCamera {
	XFov = 80,
	YFov = 80
};
cameraNode = new SCNNode {
	Camera = camera,
	Position = new SCNVector3 (0, 0, 40)
};
scene.RootNode.AddChildNode (cameraNode);

As you can see from the code above, Scene Kit objects can be created using constructors or from the Create factory method. The former allows using C# initializer syntax, but which one to use is largely a matter of preference.

With the camera in place, the entire sphere is visible to the user.

sphere

You can add additional lights to the scene as well. Here is what it looks like with a few more omni-directional lights:

sphere

Additionally, by setting sceneView.AllowsCameraControl = true, the user can change the point of view with a touch gesture.

Materials

Materials are created with the SCNMaterial class. For example to add an image onto the sphere’s surface, set the image to the material’s diffuse contents.

material = SCNMaterial.Create ();
material.Diffuse.Contents = UIImage.FromFile ("monkey.png");
sphere.Materials = new SCNMaterial[] { material };

This layers the image onto the node as shown below.

sphere

A material can be set to respond to other types of lighting too. For example, the object can be made shiny and have a its specular contents set to display specular reflection, resulting in a bright spot on the surface.

sphere

Materials are very flexible, allowing you to achieve a lot with very little code. For example, instead of setting the image to the diffuse contents, set it to the reflective contents instead.

material.Reflective.Contents = UIImage.FromFile ("monkey.png");

Now the monkey sits visually within the sphere, independent of the point of view, creating a monkey in a psychedelic 1960s sphere so to speak.

spinning monkey

Animation

Scene Kit is designed to work well with Core Animation. You can create both implicit or explicit animations. When creating an implicit animation, Scene Kit provides its own transition class, SCNTransaction.

Here’s a example that rotates the sphere:

SCNTransaction.Begin ();
SCNTransaction.AnimationDuration = 2.0;
sphereNode.Rotation = new SCNVector4 (0, 1, 0, (float)Math.PI * 4);
SCNTransaction.Commit ();

rotation

You can animate much more than rotation though. Many properties of Scene Kit are animatable. For example, the following code animates the material’s Shininess to increase the specular reflection.

SCNTransaction.Begin ();
SCNTransaction.AnimationDuration = 2.0;
material.Shininess = 0.1f;
SCNTransaction.Commit ();

shininess

As you can see, Scene Kit is incredibly easy to use. This post just scratches the surface though. There are a wealth of additional features including constraints, physics, declarative actions, 3D text, depth of field support, Sprite Kit integration and Core Image integration to name just a few. It’s exciting to see this API come to iOS 8.

The source code from this post is available here.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
June 25, 2014

Show Me the XAML

By

Xamarin.Forms brings the eXtensible Application Markup Language, or XAML as it’s so lovingly known, to cross-platform mobile development. With XAML, application user interfaces can be created declaratively and succinctly.

slider transforms via xaml

To help Xamarin.Forms developers get up to speed, our good friend Charles Petzold took a brief pause from writing his book on Xamarin.Forms to bring you this wonderful guide:

XAML for Xamarin.Forms – Getting Started with Cross-Platform Markup for Mobile Devices.

In it, you’ll find everything you need to work effectively with XAML in Xamarin.Forms. The guide includes 5 action packed parts:

Along with our other great education resources for learning Xamarin.Forms, you now have a wealth of information to help create great cross-platform apps.

TwitterFacebookGoogle+LinkedInEmail
June 24, 2014

Webinar Recording: Native Mobile Apps in Xamarin Studio

By

With an inspired development environment comprised of powerful code completion, support for TestFlight and a dynamic, modern debugger, Xamarin Studio allows developers to build better apps for iOS, Android and Mac.

In this webinar, I give a demo and in-depth look at some of our favorite Xamarin Studio features, including full support for NuGet packages, extensive documentation for the .NET Base Class Libraries (BCL), F# support, and the ability to build native user interfaces with our iOS and Android designers.

Download for Offline Viewing: http://xamarin.wistia.com/medias/z797ghqlps

Webinar slides are available on SlideShare.

TwitterFacebookGoogle+LinkedInEmail

Xamarin Studio and NuGet

By

A new version of Xamarin Studio was released as part of Xamarin 3, and one of its new features and improvements is first class support for NuGet which is now built in and fully integrated.

nugetlogo

NuGet is a package management system for .NET that simplifies the process of using third party libraries in your application. It provides access to over 20,000 third party libraries which are available from the main NuGet package gallery.

Microsoft are also embracing NuGet. Microsoft use NuGet as one of the primary ways to release libraries and have their own curated NuGet package feed.

Xamarin is also using NuGet to distribute libraries. Xamarin.Forms, the new library which allows you to build native UIs for iOS, Android and Windows Phone from a shared C# codebase, is available to download from NuGet and install into your application.

Thousands of libraries are available from NuGet, many of these are compatible with Xamarin’s frameworks, that can be used in your iOS, Android, Mac and Windows applications. There are also an increasing number of NuGet packages that contain Portable Class Libraries (PCLs), that are compatible across a range of desktop and mobile frameworks. All of these libraries are now easily available to you from within Xamarin Studio.

Xamarin Studio NuGet Features

  • Search across thousands of third party libraries available as NuGet packages.
  • Quickly add NuGet packages to your application and start using them.
  • Easily update a single package or all packages to their latest versions.
  • Automatically restore packages on opening your solution.
  • Project templates can install NuGet packages when a new project is created.
  • Consume packages from other third party NuGet package sources.
  • Search for NuGet packages from the universal search.
  • Deep integration with Xamarin Studio – integrates with the Solution window, the status bar and the universal search.

Now let us take a look at some of these Xamarin Studio features starting with adding a NuGet package to a project.

Adding a NuGet Package

With your project open in Xamarin Studio, from the Solution window, right click the project and select AddAdd Packages.

Add Packages menu option

This will open the Add Packages dialog showing you a list of NuGet packages available from the main NuGet gallery.

Add Packages Dialog

From this dialog you can search for NuGet packages and quickly add them to your project. Once you have found a package you can install it by simply selecting it and double clicking or by clicking the Add Package button. The dialog will then close and Xamarin Studio will install the NuGet package in the background. As the install proceeds Xamarin Studio’s status bar will be updated with progress messages.

StatusBarAddingXamarinForms

StatusBarXamarinFormsAdded

Detailed information on what happened during the install can be seen in the Package Console window.

Xamarin Studio Package Console Window

The Solution window will display a Packages folder which contains all the packages installed in the project.

Package Context Menu in Solution Window

From the Packages folder you can easily update a package to the latest version, or remove it from the project, by right clicking and selecting the appropriate menu item.

Assembly references added to the project by the NuGet package are displayed inside the From Packages folder in the Solution window.

Xamarin Studio From Packages Folder

Restoring NuGet packages

Xamarin Studio will automatically restore any NuGet packages that are missing when a solution is opened. This means you do not need to add NuGet packages to your source control system. Only the packages.config file for each project needs to be added to your source control system. When another developer opens the solution for the first time all the missing NuGet packages will automatically be downloaded and restored by Xamarin Studio.

Xamarin Forms Sample Packages Restored

In the screenshot above the Xamarin.Forms button source code sample, which uses NuGet packages, was opened in Xamarin Studio and the NuGet packages were automatically restored.

Project Templates with NuGet Packages

Project templates now have support for NuGet packages so Xamarin Studio can install NuGet packages when a new project is created. The project templates for Xamarin.Forms takes advantage of this feature and will install NuGet packages when a new Xamarin.Forms project is created.

Learn More

This is the end of our introduction to the NuGet support in Xamarin Studio. If you would like to learn more about Xamarin Studio then here are some more resources.

TwitterFacebookGoogle+LinkedInEmail
June 23, 2014

Using Custom Controls in Xamarin.Forms on Android

By

With over 40 pages, layouts, and controls built into the Xamarin.Forms library, you are sure to find something to fit your needs when building out native mobile apps on iOS, Android, and Windows Phone. One of the key features that I love about Xamarin.Forms is that you are able to not only completely customize each built in-control, but you can extend and mix-and-match platform specific APIs and custom controls. This means that if you have been building and using custom controls in your Xamarin apps you are still able to re-use them in your Xamarin.Forms mobile apps with the concept of a custom renderer. HoloProgressBar

Over the past 3 years I have built out a lot of custom controls and one of my favorite has to be this circular progress bar. It has the look and feel of the built in Android stop watch, but I re-wrote it in C# as part of my Xamarin.Android Toolkit. Of course I want to re-use this control and others in my Xamarin.Forms apps, so let’s take a look at how to take this pre-existing custom control and make a custom renderer for it.

Xamarin.Forms Control

There are two main parts to implementing a custom control with a renderer.

  1. Create your own custom Xamarin.Forms control with bindable properties.
  2. Create a renderer in each platform that will be used to display the custom control and subscribe to property changed notifications.

This means that you can give your custom controls new functionality with the built-in data binding system in Xamarin.Forms. In my shared code project I am going to create a new control that will be used in my pages and layouts called CircularProgress and this will inherit from Xamarin.Forms.View.

using Xamarin.Forms;
namespace CustomProgressBar.CustomControls
{
  public class CircularProgress : View
  {
    ...
  }
}

Bindable Properties

The real magic is to implement the two way data binding with custom properties in this class. I can create these with the BindableProperty class which describes what the property is and knows how to trigger a PropertyChanged Notification. Here I will implement just a few such as if the progress bar is indeterminate, the current progress, and what color the bar is.

//Bindable property for the progress color
public static readonly BindableProperty ProgressColorProperty =
  BindableProperty.Create<CircularProgress,Color> (p => p.ProgressColor, Color.Red);
//Gets or sets the color of the progress bar
public Color ProgressColor {
  get { return (Color)GetValue (ProgressColorProperty); }
  set { SetValue (ProgressColorProperty, value); }
}
...

Notice here that I am using the Color property, which is a Xamarin.Forms specific color, that I am setting to Red as the default. I would do the same for other properties that I wan to bind to.

Circular Progress Renderer

With my new Xamarin.Forms control in place I can now implement the platform specific renderer in my Xamarin.Android project, which I will call CircularProgressRenderer. Each Xamarin.Forms control has a custom renderer that you can inherit from if you are customizing a built in control. However since this is completely custom View I am going to inherit from ViewRenderer.

namespace CustomProgressBar.Droid.Renderers
{
  public class CircularProgressRenderer
    : ViewRenderer<CircularProgress, HoloCircularProgressBar> {
    ...
  }
}

This type of renderer on Android inherits from View, which means Xamarin.Forms will handle all of the size calculations and normal properties of a standard Android View. All I have to do now is create my custom control and tell the renderer to display it. I can do this in our OnElementChanged method where I have access to two very important properties.

  • First is the Element, which is our Xamarin.Forms CircularProgress control I created earlier with custom properties.
  • Second is the Control which I am able to set to whatever I would like with the SetNativeControl method.

Since ViewRenderer is templated, which you can see when I inherited from it my Element and Control already have the correct type of the Xamarin.Forms control and native control that I will be using. This means I will not have to do any casting, which is very nice.

protected override void OnElementChanged (ElementChangedEventArgs<CircularProgress> e){
  base.OnElementChanged (e);
  if (e.OldElement != null || this.Element == null)
    return;
  var progress = new HoloCircularProgressBar (Forms.Context) {
    Max = Element.Max,
    Progress = Element.Progress,
    Indeterminate = Element.Indeterminate,
    ProgressColor = Element.ProgressColor.ToAndroid(),
    ProgressBackgroundColor = Element.ProgressBackgroundColor.ToAndroid(),
    IndeterminateInterval = Element.IndeterminateSpeed };
  SetNativeControl (progress);
}

Here I am creating a new HoloCircularProgressBar from my own personal library of controls and when created I set all of the controls properties to the Xamarin.Forms control that I created and have access to before I call SetNativeControl. To get the control to show up in the actual view all I need to do is set a special ExportRenderer so Xamarin.Forms knows that my Android project has implemented this control.

[assembly:ExportRenderer(typeof(CircularProgress), typeof(CircularProgressRenderer))]
namespace CustomProgressBar.Droid.Renderers
{
  ...
}

With that in place if I setup my main page in my App.cs and use my new CircularProgress control it now shows up and renders my HoloCircularProgressBar!

return new ContentPage {
  Content = new CircularProgress {
    Progress = 25
  }
};

Xamarin.Forms Circular Progress

Handling Property Changes

I can also listen for property changed notifications in my custom control. This means I can react to any action users are performing when interacting with the Xamarin.Forms control. To do this all I need to do is override the OnElementPropertyChanged method, which is triggered whenever any bindable property is changed. The arguments that get passed in contain the property name that changed and I just need to compare it with the properties I set to update the custom control.

protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) {
  base.OnElementPropertyChanged (sender, e);
  if (this.Element == null || this.Control == null)
    return;
  if (e.PropertyName == CircularProgress.IndeterminateProperty.PropertyName) {
    Control.Indeterminate = Element.Indeterminate;
  } else if (e.PropertyName == CircularProgress.ProgressProperty.PropertyName) {
    Control.Progress = Element.Progress;
  }
  ...
}

Bringing it all together

With this code in place, I can now add a few more controls to my page that will allow me to manipulate the control directly. For instance I can add a few buttons to increase or decrease the progress, set it to indeterminate, and even bind a Slider control to change the speed.

var increase = new Button { Text = "+5" };
var decrease = new Button { Text = "-5" };
var indeterminate = new Button { Text = "Indeterminate" };
increase.Clicked += (sender, args) => progressBar.Progress += 5;
decrease.Clicked += (sender, args) => progressBar.Progress -= 5;
indeterminate.Clicked += (sender, args) => progressBar.Indeterminate = !progressBar.Indeterminate;
var slider = new Slider (50, 150, 100);
slider.ValueChanged += (sender, args) => progressBar.IndeterminateSpeed = (int)slider.Value;

Circular Progress Bar Animating n Xamarin.FormsThat is it! A fully functional and custom data bound circular progress bar all in around 100 lines of code! Here is what it looks like in action.

To learn more about customizing your Xamarin.Forms controls and applications be sure to read our thorough documentation and you can download the full source code for this project from my GitHub including a complete XAML example.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
June 20, 2014

Xamarin.Forms Contest Winners

By

In the past few weeks since we released Xamarin 3, the response from the community has been amazing, both around Xamarin 3 and Xamarin.Forms, and especially from our “Build Your First Xamarin.Forms App” contest.

After pouring through tons of great entries, it was tough to pick just one winner. Congratulations to Pete Miller for taking 1st for his entry AppyLinks! We will see you in a few months at Xamarin Evolve 2014, where you can hear from some of the industry leaders and experts in mobile development.


Coming in as a close second was Egor Bogatov’s CrossChat, a cross-platform chat application for iOS, Android, and Windows Phone. We know you’ll enjoy listening to your favorite music on Rdio for free for a year, no matter what device you carry.

CrossChat is a cross-platform chat client built with Xamarin.Forms.

Thank you to everyone who participated! We are blessed to have such a strong community around Xamarin. To show our thanks, everyone who submitted a valid entry to the contest will be receiving a monkey! If you didn’t manage to get an entry submitted this time, no worries; keep an eye on the Xamarin Blog for future contest announcements!

TwitterFacebookGoogle+LinkedInEmail
June 19, 2014

iOS 8 support

By

ios8 logoWe have just published support for Apple’s upcoming iOS 8.

Installing Xamarin.iOS for iOS 8

  • Download and install the iOS 8 SDK Beta from Apple’s iOS Developer Center.
  • Install it at the default location (do not change it).
  • Go to Xamarin Studio’s Preferences > SDK Locations > Apple and set the Apple SDK value to /Applications/Xcode6-Beta2.app
  • Switch the Xamarin Studio Updater channel to the “Alpha” channel.
  • Install the Xamarin.iOS and Xamarin Studio updates.

Windows users with Visual Studio, in addition should:

  • Switch Visual Studio Xamarin Updater Channel to “Alpha”
  • Install the Visual Studio extension update.

Getting Started

At this point, you should have the new APIs available. Check our release notes for more details and a detailed list of the new APIs.

TwitterFacebookGoogle+LinkedInEmail

3 Steps to Ship an Amazing Amazon Phone App

By

Xamarin.Android apps can run on the new Amazon Fire Phone!Yesterday, Amazon announced the Amazon Fire Phone, along with new APIs to support some exciting features for the phone through the Dynamic Perspective and Firefly SDKs. Excited to ship your Xamarin.Android apps on the Fire Phone? That’s great! Because the Fire Phone runs the Android-based Fire OS, you can already build apps for Fire OS.

Even better, because we know you’re anxious to take advantage of the Fire Phone’s unique features, we shipped a brand new component yesterday giving Xamarin developers same-day support for the Dynamic Perspective and Firefly SDKs.

The new Dynamic Perspective SDK allows developers to view things from the user’s perspective as they use apps on the device. For developers, this means you can ship fully immersive apps with head tracking and motion gesture recognition. With the Euclid 3D Framework, you can convert existing 2D controls into 3D analogs and even build your own custom 3D controls. Additionally, with the Firefly SDK, developers can now tap into the power of Amazon Web Services to easily detect and gather information about text, audio, and other visual content like images and videos.

In just three steps, you can get started integrating Amazon’s Dynamic Perspective and Firefly features into your app heading to the Amazon Appstore:

1. Install the Amazon Fire Phone Component

If you already have Xamarin installed, great news, the Component Store is available out-of-the-box for you in both Xamarin and Visual Studio. Interested in getting started developing for the new Amazon Fire Phone and don’t have Xamarin installed? Download Xamarin today and get hands-on with the new Amazon Fire Phone APIs!

2. Take Advantage of Dynamic Perspective and Firefly APIs

To get started right away with the new APIs, check out the “Getting Started” guide provided with the component. For example, the following code shows how easy it is to use advanced head tracking technology with the Dynamic Perspective SDK:

using Amazon.HeadTracking;
namespace AmazonFirePhoneApp
{
  public class ListenerActivity : Activity, IHeadTrackingListener
  {
    ...
		public void OnHeadTrackingEvent (HeadTrackingEvent trackingEvent)
		{
			var xCoordinate = trackingEvent.XMm;
			var yCoordinate = trackingEvent.YMm;
			var zCoordinate = trackingEvent.ZMm;
			var detectedFace = trackingEvent.IsFaceDetected;
			var isTracking = trackingEvent.IsTracking;
			var alert = string.Format ("X: {0}, Y: {1}, Z: {1}", xCoordinate, yCoordinate, zCoordinate);
			Toast.MakeText (this, alert, ToastLength.Short);
		}
  }
}

3. Package and Ship

On July 25th, the Amazon Fire Phone will be released to the world, but developers can submit their apps now for launch day availability, pending approval by July 18th. With the help of the Amazon Fire Phone SDK Component, you can give your apps an edge by integrating Amazon’s revolutionary new features right into your existing Xamarin.Android apps.

TwitterFacebookGoogle+LinkedInEmail
June 18, 2014

Exciting Speakers Coming to Xamarin Evolve

By

Over the past few months, we have been searching the globe to find the best speakers for Xamarin Evolve 2014, the largest cross-platform mobile development conference in the world. A few weeks ago, we announced the first round of our amazing speaker lineup. Today, we are happy to announce three more industry experts to help guide Evolve 2014 attendees on a path to mobile development success.

Jon Skeet

jon-skeet-circleJon is a software engineer at Google in London, but outside of work his passion is for C# and its community, which is why you’ll often find him writing about it on his blog, books, or on Stack Overflow. He loves twisting the language in knots, often to the horror of those he’s presenting the code to… but never for production code, of course.

Laurent Bugnion

laurent-bugnion-circleLaurent works as the Senior Director for IdentityMine in Zurich, Switzerland. This year will mark his 8th year as a Microsoft Client Development MVP and his second year as a Microsoft Regional Director. He is also the author of the well-known open-source framework MVVMLight for Windows Phone, Windows 8, WPF, and Silverlight. In his free time, Laurent writes for MSDN Magazine and various other publications, as well as on his blog at http://blog.galasoft.ch.

Joe Mayo

joe-mayo-circleJoe Mayo is an author, consultant, and instructor who specializes in Microsoft and Xamarin technologies. He has been an avid user of C# since it was first announced in July 2000, and his written six books on topics surrounding C# and .NET. For his community contributions, Microsoft has honored Joe with 10 Microsoft MVP awards over the years.

Register Now

Be on the lookout for additional speaker announcements over the coming days – and make sure to get your ticket while there are still some left.

TwitterFacebookGoogle+LinkedInEmail

Webinar Recording: Developing iOS and Android Apps in Visual Studio

By

With all of the new features and updates in Xamarin 3, developing iOS, Android, and Windows Phone apps in Visual Studio with Xamarin has never been better. The brand new Xamarin Designer for iOS enables developers to build pixel-perfect UIs for iOS with live-rendering of every control, including custom controls. Enhance your mobile development experience with features like Shared Projects, Portable Class Libraries, a streamlined installation process, and seamless integration with the Mac build host. In this webinar, I walk through all of the new features of Xamarin 3 that help enable you to design and develop beautiful native iOS and Android apps within Visual Studio.

Download for Offline Viewing: https://xamarin.wistia.com/medias/zan4ovyzui

Webinar slides are available on SlideShare.

Additional Resources:

TwitterFacebookGoogle+LinkedInEmail