Particle Designer with CocosSharp

CocosSharp comes with a variety of particle systems. For example, the GoneBananas sample uses the sun particle system (CCParticleSun) to create an animated sun, as well as the explosion particle system (CCParticleExplode) to create an explosion effect whenever the monkey collides with a banana.

GoneBananas

Although they are customizable, sometimes the built-in particle systems aren’t exactly what you want. Game developers often use particle system design tools for creating custom particle systems. One such commercial tool is the excellent Particle Designer from 71Squared.

Using Particle Designer is a great way to create custom effects and I was pleased to discover it works well with CocosSharp. For example, instead of using CCParticleExplode let’s change GoneBananas to instead use particle systems designed in Particle Designer, to create concentric exploding rings, as shown below:

particle designer

Particle Designer has an export feature that supports a variety of export formats. In this case I exported the particle systems as plist files and added them to the respective Content folders of the CocosSharp iOS and Android projects respectively.

Then, to include them in the code, create a CCParticleSystemQuad for each particle system:

var particles = new[] { "innerring.plist", "outerring.plist" };

foreach (string p in particles) {
    var ps = new CCParticleSystemQuad (p);
    ps.Position = pt;
    AddChild (ps);
}

Now when you run the game, the custom particle systems appear as shown below:

rings

Video – Build Your First iOS App with Visual Studio and Xamarin

Here’s a video I made for Microsoft’s Flashcast series showing how to develop an iOS application using Visual Studio:



My colleague James did one for Android as well: http://flashcast.azurewebsites.net/stream/episode/5

Later this month we’ll have more Flashcasts, including one that shows how to use Xamarin’s iOS Designer for Visual Studio, and another on Xamarin.Forms. Keep an eye out for these, as well as other great topics at http://flashcast.azurewebsites.net

Using Twilio with Xamarin

Twilio recently published a great component to enable iOS and Android apps developed with Xamarin to easily add VoIP capabilities.

twilio component

This post walks through making a simple app to call a phone number.

Setting up the Twilio Server

The first thing you need to do is sign up for a Twilio account. They have a free trail version, which you can sig nup for at https://www.twilio.com/try-twilio, that will work fine for our purposes.

Before getting started there is a bit of setup you’ll need to perform in the Twilio portal.

When you set up a Twilio account, you’ll be given a Twilio phone number. You can view your phone number at any time by selecting the “Numbers” section in the Twilio user account page:

twilio_numbers

You’ll also need your account SID and auth token, which you can get under the “dashboard” section of the account page.

dashboard

The last thing you’ll need to create is a TwiML app, which you can do under “Dev Tools” > “TwiML Apps”. Set the app url to http://YourDomain/InitiateCall as shown below:

twiml_apps

Note the SID here is the application SID,as opposed to the account SID shown earlier.

We these things in place, you’re ready to get started coding. Twilio requires a server to handle token generation and in this case, the TwiML app to initiate the call.

A free ASP.NET MVC website in Azure works fine. Here’s the full code for the ASP.NET MVC controller for this example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

namespace TokenGenerator.Controllers
{
    public class ClientController : Controller
    {
        public ActionResult Token(string clientName = "default")
        {
            string accountSid = "Your account SID";
            string authToken = "Your auth token";
            string appSid = "Your app SID";
                
            var capability = new TwilioCapability(accountSid, authToken);
            capability.AllowClientIncoming(clientName);
            capability.AllowClientOutgoing(appSid);

            return Content(capability.GenerateToken());
        }

        public ActionResult InitiateCall(string source, string target)
        {
            var response = new TwilioResponse();
            response.Dial(target, new { callerId = source });

            return new TwiMLResult(response);
        }
    }
}

For the above code, you’ll also need to add a couple NuGet packages:

  • Twilio.Mvc
  • Twilio.Client

Then, simply replace the accountSid, authToken and appSid with the values obtained above and publish the site to Azure.

Using the Xamarin Twilio Component

For this example I’m just going to create a simple iOS client to make an outgoing call. However, Android is supported as well.

In a new iOS project create 3 buttons named callButton, hangUpButton and sendKeyButton (I used a storyboard to create the UI) and add the following code to the view controller.

using System;
using System.Net.Http;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using TwilioClient.iOS;

namespace HelloTwilio
{
    public partial class HelloTwilioViewController : UIViewController
    {
        TCDevice device;
        TCConnection connection;

        public HelloTwilioViewController (IntPtr handle) : base (handle)
        {
        }

        public async override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            var client = new HttpClient ();
            var token = await client.GetStringAsync ("http://YourSite/Client/Token");

            device = new TCDevice (token, null);
			
            callButton.TouchUpInside += (object sender, EventArgs e) => {

                string twilioNumber = "Your twilio number";
                string numberToCall= "Some number to call";

                var parameters = NSDictionary.FromObjectsAndKeys (
                    new object[] { twilioNumber, numberToCall }, 
                    new object[] { "Source", "Target" }
                );
        
                connection = device.Connect (parameters, null);
            };

            sendKeyButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.SendDigits ("1");
                }
            };

            hangUpButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.Disconnect ();
                }
            };
        }
    }
}

In the code, set the domain name you published to earlier where it says “YourSite” and add your Twilio number and a phone number to call respectively.

Adding the Twilio component is easy. Just right-click on “Components” in the Solution Explorer, select “Get More Components”, and pick the Twilio component.

Once the component is added, run the application and click “Call”. After hearing the trial account message, press the “Send Key 1” button and the phone call will be initiated.

phone app

There you have it, VoIP added to an iOS app. Pretty cool 🙂

Xamarin Getting Started Sampler

There are many great resources for learning Xamarin, ranging from docs, samples and videos, to full-blown training via Xamarin University. If you’re just getting started, here are a list of resources to get you off to a good start. There are many other articles and samples as well in the Xamarin Developer Center, so it really depends upon your interests, but these are good fundamental topics in any case:

Xamarin.iOS:

Xamarin.Android:

Xamarin.Forms:

Also see:

And check out the recipes, samples and videos sections as well:

Draw a PDF in Landscape with Core Graphics

I just got a question from a Core Graphics presentation I gave a while back (from the first Xamarin Seminar) about how to use Core Graphics to render a PDF with 2 pages side-by-side in landscape. Since this question has come up a couple times in the past I figured I’d write a blog post about it.

The solution I use for this is to create a rectangle to display each page and then apply a transform to render the page within the rectangle. CGPDFPage has a handy GetDrawingTransform function that returns the transform. To get back a transform that crops the page to the rectangle while preserving the aspect ratio simply call:

CGAffineTransform transform = 
    pdfPage.GetDrawingTransform (CGPDFBox.Crop, pageRectangle, 0, true);

To do this for 2 pages, use the SaveState and RestoreState functions of the CGContext to get the transformation matrix back to its intial state, so that the transformation of the first page isn’t applied to the second page.

The following code shows how to implement this in a UIView subclass:

public override void Draw (RectangleF rect)
{
    base.Draw (rect);

    var rect1 = new RectangleF (0, 0, Bounds.Width / 2, Bounds.Height);
    var rect2 = new RectangleF (Bounds.Width / 2, 0, Bounds.Width / 2, Bounds.Height);
    
    using (CGContext gctx = UIGraphics.GetCurrentContext ()) {
        gctx.TranslateCTM (0, Bounds.Height);
        gctx.ScaleCTM (1, -1);

        gctx.SaveState ();

        using (CGPDFPage page = pdf.GetPage (page1)) {
            CGAffineTransform transform = 
                page.GetDrawingTransform (CGPDFBox.Crop, rect1, 0, true);
            gctx.ConcatCTM (transform);
            gctx.DrawPDFPage (page);
        }

        gctx.RestoreState ();

        using (CGPDFPage page = pdf.GetPage (page2)) {
            CGAffineTransform transform = 
                page.GetDrawingTransform (CGPDFBox.Crop, rect2, 0, true);
            gctx.ConcatCTM (transform);
            gctx.DrawPDFPage (pdfPg);
        }
    }
}

This renders the PDF to the screen as shown below:

landscapepdf

Use Nokia X HERE Maps with Xamarin.Android

Earlier this week Nokia announced their new line of Nokia X Android phones. C# developers using Xamarin can target this platform via the Nokia components in the Xamarin Component Store.

Let’s take a look at using the Nokia HERE Maps API in a Xamarin.Android applcation.

Nokia HERE Maps have a wealth of features ranging from 3D landmarks, to street-level imagery and venue maps.

here_map

See the HERE Maps section of the Nokia developer site for more information on the entire feature set.

The first thing you need to do is set up the Nokia X Platform, which can be done via the Android SDK Manager. The following doc on the Nokia developer site explains how to do this:

http://developer.nokia.com/resources/library/nokia-x/getting-started/environment-setup.html

Note, when you create a Nokia X emulator, be sure to set the target to Nokia X services (Nokia) – API Level 16 as shown below:

nokiax_emulator_setup

Once you have your environment set up, create a new Android project that targets API level 16. To use Nokia HERE Maps from Xamarin, simply add the Xamarin component:

http://components.xamarin.com/view/NokiaHERE

The component brings everything you need directly into the project in either Visual Studio or Xamarin Studio. The sample projects included with the component show you how to get started.

Adding a Map

Basically, to include a map:

  1. Add your AppID and AppToken
  2. Set the required permissions
  3. Add a MapFragment
  4. Initialize the MapFragment
  5. Setup the map after the fragment has been initialized

AppID and AppToken

The AppID and AppToken can be set using attributes:

[assembly: MetaData("com.here.android.maps.appid", Value = "YourAppID")]
[assembly: MetaData("com.here.android.maps.apptoken", Value = "YourAppToken")]

Also, enable hardware-accelerated rendering:

[assembly: Application(HardwareAccelerated = true)]

Required Permissions

Next, the following required permissions need to be set in the Android manifest:

  • AccessFineLocation
  • AccessNetworkState
  • AccessWifiState
  • ChangeNetworkState
  • Internet
  • WriteExternalStorage

MapFragment

The Sample.HERE application included with the component adds the MapFragment in code via the FragmentManager:

fragment = new MapFragment ();
FragmentManager.BeginTransaction ()
  .Replace (Resource.Id.fragmentcontainer, fragment).Commit();

Additionally, you can add the MapFragment in the axml file, which is what I’ve done in this example:

Then in the Activity’s OnCreate method, retrieve the MapFragment and initialize it as follows:

mapFragment = FragmentManager.FindFragmentById (Resource.Id.mapfragment);
mapFragment.Init (this, this);

Accessing the Map Object

To get a reference to the map itself after the fragment initialization has completed, implement the IFragmentInitListener from the Nokia.Here.Mapping namespace, where you can access the map via the MapFragment’s Map property. Then you can call methods on the map such as SetCenter and SetZoomLevel:

public void OnFragmentInitializationCompleted (InitError error)
{
  if (error == InitError.None) {
    map = mapFragment.Map;

    double lat = 30.2652233534254;
    double lon = -97.73815460962083;

    map.SetCenter (MapFactory.CreateGeoCoordinate (lat, lon, 0.0), MapAnimation.None);
    map.SetZoomLevel (18.0, MapAnimation.None);
  }
}

This displays a map in the application as shown below:

nokiax_map

There are variety of map schemes that can be easily set via the MapScheme property. For example, setting map.MapScheme = MapScheme.SatelliteDay will show a map with daytime satellite imagery:

nokiax_satellite

See Nokia Map Schemes documentation for the other schemes that are available.

As you can see, it’s pretty easy to get started. There are wealth of additional feature as well. For example, you can add a polygon to a map using the MapFactory class to create an IMapPolygon:

var geoPolygon = MapFactory.CreateGeoPolygon (new JavaList {
  MapFactory.CreateGeoCoordinate (30.2648461170005, -97.7381627734755),
  MapFactory.CreateGeoCoordinate (30.2648355402574, -97.7381750192576),
  MapFactory.CreateGeoCoordinate (30.2647791309417, -97.7379872505988),
  MapFactory.CreateGeoCoordinate (30.2654525150319, -97.7377341711021),
  MapFactory.CreateGeoCoordinate (30.2654807195004, -97.7377994819399),
  MapFactory.CreateGeoCoordinate (30.2655089239607, -97.7377994819399),
  MapFactory.CreateGeoCoordinate (30.2656428950368, -97.738346460207),
  MapFactory.CreateGeoCoordinate (30.2650364981811, -97.7385709662122),
  MapFactory.CreateGeoCoordinate (30.2650470749025, -97.7386199493406)
});

MapPolygon’s are one of many MapObjects. These are added to the map by calling AddMapObject:

map.AddMapObject (mapPolyline);

With this, we get an overlay of the specified coordinates:

nokiax_mappolygon

You can download the sample code shown here from my github repo.

Core Animation Resources for Xamarin.iOS Developers

If you are an iOS developer, you owe it to yourself to try and learn the Core Animation framework because it isn’t just about animation. Core Animation makes much of what you see in iOS applications possible.

Here are some resources to get  you started:

Going through these resources will give an understanding of how the Core Animation framework is at the heart of iOS, which will help you to create experiences that differentiate your application.

MonkeySpace 2013

Last week I was lucky enough to attend the MonkeySpace conference, where I got to present 3 different talks. This is one of my favorite conferences as the attendees tend to work on some very interesing projects and have an affinity for sharing information.

The first talk I gave was about collection views. This is a very interesting technology that allows you to easily create grid-like layouts of items in iOS. Additionally, they are easy enough to extend to create any sort of layout you can imagine.

Here’s one of the examples I demonstrated during my talk. It creates a layout over a baseball field where you can toggle between the home and away teams:

BaseballLayout

The code is available here:

https://github.com/mikebluestein/CVLayoutsDemo

Up next, I presented the latest version of the excellent Xamarin.Mobile API, showing the new changes to the MediaPicker among other things. What’s particularly exciting about this is the API was open-sourced just before my talk, so I was able to demonstrate from the latest source.

Finally, for my third talk, I showed how to make a small game using the new Cocos2D-XNA API, a C# port of the widely used Cocos2D iOS API. What’s interesting about Cocos2D-XNA is that it builds on MonoGame, so it allows you to reach many platforms with the same code base.

http://www.slideshare.net/mikebluestein1/cocos2-d-xna

More information, along with sample code can be found in the article I wrote on the Xamarin site:

http://docs.xamarin.com/guides/cross-platform/cocos2d_xna/cocos2dxna_tutorial

Beyond my talks, I really enjoyed meeting so many new people and hearing about all the exciting work everyone is doing. I’m looking forward to MonkeySpace again next year!