Category Archives: Hacking

I’m building an Atom Simulation with SkiaSharp and Xamarin.Forms!

So lately I’ve been on quite a bunch of adventures with SkiaSharp in Xamarin.Forms! 😀 You know how it is for me, pushing the limits of the framework as usual for the fun 😉 And this right here is one of those adventures I’m going to share with you all…

Little Backstory…

I’ve always been fascinated by the Atom’s graphical structure being the science nerd back in school days. I’ve always loved the simulation of the Electrons circulating around the atom’s core filled with Neutrons and Protons. 😀 So while reminiscing those memories, I was thinking of ways to play around with SkiaSharp framework, and suddenly, AHA! A light bulb lit-up on my head! 😀

I’ve decided to build an Atom Simulation in SkiaSharp, with Xamarin.Forms! 😉

A sneak peek!

  

TADAAA! 😀

So where is it going?

Haven’t you ever thought those animated atom structure simulation they show on TV was very very cool? Well I’m thinking of building a similar simulation with SkiaSharp on top of Xamarin.Forms! 😀

And this is going to be a step by step process, where I shall begin with the basic 2D structure and slowly moving towards the complex animated simulation!

Well I’ve already started developing this some time back, and I’ve made quite a bit of progress.

I have hosted this on Github: github.com/UdaraAlwis/SkiaSharpAtomStructureSo that anyone can try it out or add improvements to it, and yes I’m open for pull requests! 😉

Code behind tech bits?

Well basically as you may have already figured out, it’s a Xamarin.Forms project, and I’m using the awesome SkiaSharp for rendering the graphics.

And to be specific with SkiaSharp I’m using the following to render the cool stuff:

  • 2D Shapes Drawing
  • Canvas Translations and Rotations
  • Continuous Animation Rendering
  • Gradient Shading
  • Touch handling

Pretty cool set of features right there, out of the box with SkiaSharp eh! 😉

Progress so far…

I’ve broken the progressive steps to several Pages in the project for clear distinction between the code behind.

I will be updating this post as the project moves forward with improvements and new progression steps.

And here they are…

1. Atom Silhouette

 

So the first step was to simply build a silhouette of the atom structure. There you have the core with Neutrons and Protons, and the Electrons around it in their own orbits.

Basically I’m using the SkCanvas.DrawCircle() to draw the center core and then SkCanvas.DrawOval() to draw the Oval Orbits around the core. 😉

Then I’m drawing the “Electron dot” for each orbit using the corner most point of the Oval Orbit, which is basically the width of the Oval. Tricky yeah!

You might think how about the angles of the oval? Oh yeah I’m using Canvas Rotation for each orbit draw cycle, SkCanvas.RotateDegrees(xx degrees)! 😀

And there’s a simple +/- increment mechanism for increasing and decreasing the number of electrons around the orbit!

You can take a look at the implementation: AtomSilhouettePage.xaml.cs

2. Atom Orbital Paths

 

Here’s a little improvement for the previous step, where as I’ve added some gradient effect for the drawing of the Oval path with the same SkCanvas.DrawOval() call.

The CreateSweepGradient() is one of the way to create a gradient color effect in SkiaSharp, whereas we’ve used white and dark gray as the color here.

Oh Gradients are always cool yeah! 😉

You can take a look at the implementation: AtomOrbitalPathsPage.xaml.cs

3. Atom Orbital Paths Uneven

 

Now we know in reality the Atom’s electron orbit is not a nice even orbit, so we’re going to reflect just that in this progress step! 😀

So basically I’m randomly generating the Oval’s supposed width for each orbit, thus giving the above output!

You can take a look at the implementation: AtomOrbitalPathsUnevenPage.xaml.cs

4. Atom Animated Silhouette

 

This is the step where I kick it up a notch, with the Animation rendering using SkiaSharp!

So as we all know there’s no direct animation rendering support with SkiaSharp, since its a on demand 2D vector graphics rendering system.

What I’m doing here to get the electron dot’s to movement on the oval orbit, is I’m rendering it’s each 360 degrees positions continuously on a timer loop. Might sound pretty complex, but its actually simple! 😉

You can take a look at the implementation: AtomAnimatedPage.xaml.cs

5. A cool touch feature!

I’ve added something cool for the number of displayed Electron’s incremental mechanism!

 

I’ve added a touch handling feature to the atom’s electron incremental mechanism, so now basically you can swipe up or down the screen to increase or decrease the number of electron orbits of the Atom! 😉 Now instead of clicking on the +/- buttons, rather you could swipe up or down to increase or decrease the electron orbits.

This was done simply using the SkiaSharp’s built in touch event handler, and calculating the touch movement direction, thus determining up or down direction! 😀

6. Atom Animated Uneven Orbits

 

So here’s the next progression step, with uneven orbits animation! I’m using a gradient oval drawing for each orbit, similar to what I’ve explained above in one of the previous steps. And I’m generating the Orbits Width upon a given random value.

You can take a look at the implementation: AtomAnimatedUnevnOrbitsPage.xaml.cs

7. ….T B C…..

This will be the next progression step. Since this post will be a continuously updated post along with every progression step I make in this fun project! 😀 So stay tuned!

 

 

That’s all for now!

So like I said at the beginning, this is a continuous fun protect, which I’ll keep on improving step by step. And once again, I will be accepting your pull requests for any improvements you suggest, or just drop a comment or message me of your suggestions. 😀

Don’t forget, feel free to try this project from my Github repo: github.com/UdaraAlwis/SkiaSharpAtomStructure 

I will be updating this post as the project progresses on hopefully! 😉

Advertisements

An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! ;)

Imagine you wanted to prompt your user with a popup alert dialog (which is also transparent, because its cool! lol) 😉 asking them to enter some value and you want to await the whole task (make it awaitable) while you’re at it, so the execution will halt until the user enter the value, and then retrieve the user entered value to the point of origin? 😀

And just to add some sugar to it, may be you wanted to customize and decorate the appearance of the input view?

Something like this?

Seems pretty cool yeah! That’s what I’m gonna share today!

Right outta Xamarin.Forms?

Now there’s no way you could do either of those things in that scenario right out of Xamarin.Forms! Nope, not with a Modal Popup, which doesn’t support transparency, and not even with DisplayAlerts or ActionSheets, since the’re not customizable, they don’t allow text input or any kind of custom input view, only multiple button selections.

So how could I do it?

Let me explain fellas!

So for transparency and ultimate flexibility of setting up custom popup views, we are going to use the awesome Rg.Plugins.Popup library for Xamarin.Forms and to make the whole Task awaitable let’s use a TaskCompletionSource (Thank you dot net)! 😉

So the trick here for adding custom input views to the popup page, is by creating our Xamarin.Forms custom views using a ContentView and set them to the Content of popup page.

Alright then time for some coding!

Let the coding begin…

But first, setting up!

First thing first create a Xamarin.Forms PCL project in Visual Studio. 🙂

Then install Rg.Plugins.Popup library for Xamarin.Forms through Nuget Package manager.

I’ve actually written a blog post about Rg.Plugins.Popup in my blog right here: So I created a Popup with Transparent background in Xamarin Forms… 😉

Create the Transparent Popup Page…

Once you’re done with that, let’s create our custom Transparent Popup Page using the Rg.Plugins.Popup we just installed.

Something to keep in mind,

  • We should allow it to use Generic data types as for the return data type. 😀
  • Popup page provides us with many cool features, including Page background click handling and back button press handling, which we will override as of disable page background click to dismissal and disable back button press cancellation.
  • Pass in a View and set it to the PopupPage’s Content property, which we will attach the custom input view we want to use in our popup page.
  • Set the transparency level to 0.4 of alpha value.

Let’s call it InputAlertDialogBase.

/// <summary>
/// The awesome Transparent Popup Page
/// sub-classed from Rg.Plugins.Popup
/// Customized for our usecase with
/// Generic data type support for the result
/// </summary>
/// <typeparam name="T"></typeparam>
public class InputAlertDialogBase<T> : PopupPage
{
	public InputAlertDialogBase(View contentBody)
	{
		Content = contentBody;

		this.BackgroundColor = new Color(0, 0, 0, 0.4);
	}

	// Method for animation child in PopupPage
	// Invoced after custom animation end
	protected override Task OnAppearingAnimationEnd()
	{
		return Content.FadeTo(1);
	}

	// Method for animation child in PopupPage
	// Invoked before custom animation begin
	protected override Task OnDisappearingAnimationBegin()
	{
		return Content.FadeTo(1);
	}

	protected override bool OnBackButtonPressed()
	{
		// Prevent back button pressed action on android
		//return base.OnBackButtonPressed();
		return true;
	}

	// Invoced when background is clicked
	protected override bool OnBackgroundClicked()
	{
		// Prevent background clicked action
		//return base.OnBackgroundClicked();
		return false;
	}
}

 

There you go, over to the next step!

Configure the await-able Task properties…

So let’s create a Task and TaskCompletionSource inside our InputAlertDialogBase, to handle await-ability of our “Transparent, Custom, Popup Input Dialog” as I’ve mentioned in the blog title! 😉

public class InputAlertDialogBase<T> : PopupPage
{
	// the awaitable task
	public Task<T> PageClosedTask { get { return PageClosedTaskCompletionSource.Task; } }

	// the task completion source
	public TaskCompletionSource<T> PageClosedTaskCompletionSource { get; set; }

	public InputAlertDialogBase(View contentBody)
	{
		...

		// init the task completion source
		PageClosedTaskCompletionSource = new System.Threading.Tasks.TaskCompletionSource<T>();

		...
	}

	...
}

 

Note that how we are initializing the TaskCompletionSource in the Constructor.

Alright, now our Transparent Popup is ready. Next we need to construct the Custom Input View, that we are going to pass into the InputAlertDialogBase to display and retrieve data input (text or any kind) from the User. 😀

Create your Custom Input View! 😀

Alright this step is totally up to your desires, you could construct any kind of a Custom Input View to be displayed on top of the InputAlertDialogBase we just created above, and retrieve the User’s inputs.

So for this example, let’s create a simple View with Title Label, Text Entry and Ok button yeah! 😉 Also let’s add a simple validation Label inside it to show up if the User tries to leave the Text Entry empty and hit the ok button to quit.

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    x:Class="XFCustomInputAlertDialog.InputViews.TextInputView"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentView.Content>
        <StackLayout
            Padding="10"
            BackgroundColor="White"
            HorizontalOptions="CenterAndExpand"
            Spacing="5"
            VerticalOptions="CenterAndExpand">
            <Label
                x:Name="TitleLabel"
                FontSize="Medium"
                Text="Enter the value:" />
            <Label
                x:Name="ValidationLabel"
                FontSize="Micro"
                IsVisible="False"
                Text="You can't leave this field empty!"
                TextColor="Red" />
            <Entry x:Name="InputEntry" Placeholder="Enter Here..." />
            <Button x:Name="CloseButton" Text="Ok">
                <Button.HeightRequest>
                    <OnPlatform x:TypeArguments="x:Double">
                        <On Platform="Android" Value="40" />
                        <On Platform="iOS" Value="30" />
                    </OnPlatform>
                </Button.HeightRequest>
            </Button>
        </StackLayout>
    </ContentView.Content>
</ContentView>

 

As you can see we have created a simple ContentView with a custom Text input view! 😀

Notice that we have explicitly named all the elements and added a button click event, this is to make it easy to set custom textual values to the elements and to handle the OK button’s click event as for the closing of the Popup Page. 🙂

Pretty simple yeah, next let’s handle the back end of this custom View to manage the Textual values, Ok button’s click event and validations.

Let’s manage code-behind of Custom Input View…

Now this is important, if you consider a ContentView, all it’s Child elements are private to it’s class scope, so we can’t observe or interact with any of the property value changes or behaviors from outside of the View.

Therefore we need to create custom properties that will expose those required values and events to the public.

Something to keep in mind here,

  • In order to customize the values displayed in the Child elements of the ContentView (Label,Button, etc..) we should pass in the values to the Constructor and set them to the Child elements there.
  • We should create a public EventHandler to handle the Ok Button’s click event from outside the View and add a public string Propery to expose the text Entry’s value to the public.
  • Subscribe to the Entry’s TextChanged event to reflect the value the public string property.
  • Create a public bindable Boolean property to display or hide Validation label in the ContentView. Or you could handle this internally in the View on the Ok Button’s click event as well, but it would be nice if we could expose the Validations to public so we could handle it outside the View.

public partial class TextInputView : ContentView
{
	// public event handler to expose 
	// the Ok button's click event
	public EventHandler CloseButtonEventHandler { get; set; }

	// public string to expose the 
	// text Entry input's value
	public string TextInputResult { get; set; }

	public TextInputView(string titleText, 
          string placeHolderText, string closeButtonText, 
           string validationLabelText)
	{
		InitializeComponent();

		// update the Element's textual values
		TitleLabel.Text = titleText;
		InputEntry.Placeholder = placeHolderText;
		CloseButton.Text = closeButtonText;
		ValidationLabel.Text = validationLabelText;

		// handling events to expose to public
		CloseButton.Clicked += CloseButton_Clicked;
		InputEntry.TextChanged += InputEntry_TextChanged;
	}

	private void CloseButton_Clicked(object sender, EventArgs e)
	{
		// invoke the event handler if its being subscribed
		CloseButtonEventHandler?.Invoke(this, e);
	}

	private void InputEntry_TextChanged(object sender,
					TextChangedEventArgs e)
	{
		// update the public string value 
		// accordingly to the text Entry's value
		TextInputResult = InputEntry.Text;
	}
}

 

So you can see we are passing in all the required values to set to our Child element’s we are passing in to the Constructor and setting them up there. Also we are subscribing to the Ok Button’s OnClick event and text Entry’s TextChanged event.

Inside the CloseButton_Clicked() event we are invoking the public EventHandler CloseButtonEventHandler if it’s being subscribed to by outside.

As well as  the Entry’s InputEntry_TextChanged() event we are updating the public TextInputResult to reflect the Entry’s text value to the public.

Don’t forget to handle Validations…

Oh and here’s the Bindable Boolean property you should include inside the TextInputView code behind to handle the Validations from outside the View.

public partial class TextInputView : ContentView
{
	...
	
	public static readonly BindableProperty 
           IsValidationLabelVisibleProperty =
		BindableProperty.Create(
			nameof(IsValidationLabelVisible),
			typeof(bool),
			typeof(TextInputView),
			false, BindingMode.OneWay, null,
			(bindable, value, newValue) =>
			{
				if ((bool)newValue)
				{
					  
		((TextInputView)bindable).ValidationLabel
					 .IsVisible = true;
				}
				else
				{
					 
		((TextInputView)bindable).ValidationLabel
					.IsVisible = false;
				}
			});

	/// <summary>
	/// Gets or Sets if the ValidationLabel is visible
	/// </summary>
	public bool IsValidationLabelVisible
	{
		get
		{
			return (bool)GetValue(
                             IsValidationLabelVisibleProperty);
		}
		set
		{
			SetValue(
                         IsValidationLabelVisibleProperty, value);
		}
	}
	
	...
}

 

Now speaking of the bindable IsValidationLabelVisibleProperty, we are updating the Validation Label’s visibility based on its value changes accordingly. 🙂

Following this method, you can create any kind of custom Input Views to be attached to our Transparent Popup Page. 🙂 All you need to do is expose the required Values and Events to the public.

Alright next step…

Time to assemble everything and consume it!

Now we are going to put everything together and get it to be used as our “awaitable Transparent, Custom, Popup Input Dialog”! 😉

Somethings to keep in mind here,

  • We need to initialize our TextInputView by passing in the parameters we would like the necessary child elements to display
  • Create an InputAlertDialogBase<string>(), yes of type string, since we are going to return a string from the Popup Alert.
  •  Subscribe to the CloseButtonEventHandler of TextInputView’s instance to handle validation and reflect the Text input value to the TaskCompletionSource.
  • Push the popup page instance to Navigation Stack and await the page’s Task
  • Upon result retrieval Pop the page from Stack and return the user inserted value.

Alright let’s do it…

private async Task<string> LaunchTextInputPopup()
{
	// create the TextInputView
	var inputView = new TextInputView(
		"What's your name?", "enter here...", 
		"Ok", "Ops! Can't leave this empty!");

	// create the Transparent Popup Page
	// of type string since we need a string return
	var popup = new InputAlertDialogBase<string>(inputView);

	// subscribe to the TextInputView's Button click event
	inputView.CloseButtonEventHandler +=
		(sender, obj) =>
		{
			if (!string.IsNullOrEmpty(
                         ((TextInputView)sender).TextInputResult))
			{
				
                            ((TextInputView)sender)
                               .IsValidationLabelVisible = false;
				
                            // update the page completion source
                            popup.PageClosedTaskCompletionSource
                                .SetResult(
                                ((TextInputView)sender)
                                      .TextInputResult);
			}
			else
			{
				
                             ((TextInputView)sender)
                                 .IsValidationLabelVisible = true;
			}
		};

	// Push the page to Navigation Stack
	await PopupNavigation.PushAsync(popup);

	// await for the user to enter the text input
	var result = await popup.PageClosedTask;

	// Pop the page from Navigation Stack
	await PopupNavigation.PopAsync();

	// return user inserted text value
	return result;
}

 

There you go, step by step as I explained before you can see how it’s being consumed. Specially inside the CloseButtonEventHandler, every time the event fires we are checking the TextInputResult property and enabling or disabling the IsValidationLabelVisible property, as well as updating the PageClosedTaskCompletionSource property value if a text value is being entered by the User, which will in return update the awaiting PageClosedTask and task will proceed to completion state, then return the value after popping the Page. 😀

There you go! 😀 How straight forward is that! 😉

Keep in mind like I said before you can add any kind of a customized View on top of our Transparent Popup Page, and retrieve any kind of result as you expect from the User following the same steps. 😀

Let’s see this in action…

 

Look at that coolness right! 😉

Since it’s full on Xamarin.Forms, and doesn’t have a single line of native code, you could straight up run this implementation on all Android, iOS, UWP, WinPhone as you wish! 😀

I want more! 😮

Alright now that’s just a little bit of basic head start of what you could do, whereas if you get creative and smart you could do a lot more cool stuff like this…

  

 

 

There you have it, some cool stuff I played around with my implementation. 😉

You can grab the Github code from here: github.com/UdaraAlwis/XFCustomInputAlertDialog

Well fellas, that’s it for now!

Enjoy! 😀 Share the love!

-Udara Alwis 😀

Forcefully dismissing Keyboard in Xamarin Forms…

Wait… what? You want to forcefully dismiss your keyboard? A-B-S-O-L-U-T-E-L-Y!

Thanks to my experience in  working with high-expectation- seniors at my company, who demands me to push the limits of the Xamarin Forms Framework (frankly I love it, although it is kind of exhausting at times), I keep on sharing cool stuff which is quite out of the norm. And heyyy buckle up, since this is one of those instances where I pushed the limitations of Xamarin Forms! 😉

Once upon a time…

So there was this one time where I had to mimic a translucent layer on top of a login screen, where once the user enters username and password, I would simple capture a screenshot, blur it, and display as a blurred view on top of the page. But the problem there was as soon as user hits “Enter” on the keyboard, the screenshot will be captured but the keyboard would also be visible in the screenshot, since keyboard still stays up until a new layer is popped on top of the page (until the Entry’s focus is dismissed). 😦

Thereby the screenshot and the blurred view had the Keyboard visibility, which was pretty ugly, and my UX Lead wasn’t happy about it (perfectionists! lol).

“YOU MUST GET RID OF THE KEYBOARD VISIBILITY INSTANTLY, NO EXCUSE!”, demanded the UX Lead. 😮

Although this was no way possible out of the box from Xamarin Forms, I was asked to get rid of it one way or the other.

Nah I Didn’t give up!

You might think it’s just a matter of dismissing the focus of the Entry’s Completed event, but hell no it wasn’t! Because there was a specific delay from the Completed event to the keyboard dismissal event firing, which caused our screenshot capturing to capture the page with the Keyboard in view. 😮

So I knew I had to override or interrupt or short-wire the keyboard dismissal event myself forcefully. 😉

So after trying out many different solutions to get rid of the Keyboard visibility when the screenshot was captured, which ended up failing, I finally had the moment of “eureka!”.

le moment of eureka! 😀

Basically, what I did was to create a dependency service which would forcefully dismiss the keyboard, as in, push down the keyboard from which ever the current view of focus.

Sounds pretty simple eh? nah it wasn’t. lol

Up on the Entry’s Completed event I would first of all call up on my custom Keyboard dismissal service and then perform the screen capture and blurring view effect and so on. Which worked out pretty nicely!

Behold the results…

Yeah here’s something I built up to demonstrate the awesomeness of this hack!

How cool is that right? 😉

Besides the coolness, now you might ask what else could this be used for? Isn’t that obvious bro? 😛

Instances where,

  • you want to limit the user from entering text into an Entry after a given timeout?
  • may be dismiss the keyboard after a certain text length is reached?
  • instantly dismiss the keyboard straight from the ViewModel itself without having to go through a UI Event chain?

and so many other aspects, or it might as well be the same situation I had. 😉

Let me show you how it’s done…

So there’s no doubt we need to drill down to the native level when we try to push the limits of Xamarin Forms Framework, as usual.

In Android we could gain the access for the InputMethodManager which gives us the capability to hide the keyboard on demand.

And on iOS we use the UIApplication instance which gives us the access to the PresentedViewController property (current active ViewController), in return allowing us to call the EndEditing on its View to resign the first responder.

Finally I unite those two native calls via dependency service and be used from Xamarin Forms PCL level.

Here’s how to code it…

Blah blah blah.. yeah I talk too much when I’m enthusiastic about a hack I came across lol! 😀

First step create the interface for the keyboard dismissal service…

namespace WhateverYourNamespace
{
    /// <summary>
    /// Forcefully dismiss the keyboard
    /// </summary>
    public interface IForceKeyboardDismissalService
    {
        void DismissKeyboard();
    }
}

 

Now we could use this interface to do the native implementations which could be used via DependencyService of Xamarin Forms.

Next native hacking… or short circuiting you could say!

This is the time for native project level implementation of our service. Go ahead create your platform specific implementation of the IForceKeyboardDismissalService interface.

So for Android, we need to access the current Activity to access the InputMethodManager, for which we would use the Plugin.CurrentActivity library. So if you don’t have it, you might as well go ahead add that to your solution via nuget before implementing the below.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidForceKeyboardDismissalService))]
namespace WhateverYourNamespace.Droid
{
    public class AndroidForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            InputMethodManager imm = InputMethodManager.FromContext(CrossCurrentActivity.Current.Activity.ApplicationContext);

            imm.HideSoftInputFromWindow(
                CrossCurrentActivity.Current.Activity.Window.DecorView.WindowToken, HideSoftInputFlags.NotAlways);
        }
    }
}

 

As you can see we are calling up the HideSoftInputFromWindow() method to dismiss the Keyboard via the InputMethodManager instance we retrieved.

Oh don’t forget to add the assembly attributes to register this for the Xamarin Forms DependencyService.

Then on iOS, we already have the singleton access to UIApplication where we are given access to the active PresentedViewController, which holds the instance for the current active view controller.

[assembly: Xamarin.Forms.Dependency(typeof(IosForceKeyboardDismissalService))]
namespace WhateverYourNamespace.iOS
{
    public class IosForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                var window = UIApplication.SharedApplication.KeyWindow;
                var vc = window.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }

                vc.View.EndEditing(true);
            });

        }
    }
}

 

Alright we are then calling the EndEditing() method from the current active View related to the active ViewController. There we are passing true as the parameter to let it know we mean business! 😛 lol uikit/uiview/1619630-endediting

Alright now time for the consumption of some cool code.

Consume it. (not literally) 😛

Here’s how you could use the above awesome service in Xamarin Forms.

DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();

 

That’s it!

Where’s the cool demo? 😮

Now don’t worry I shall not leave you hanging fellas!

You may be wondering where’s the cool implementation you saw at the beginning of the post… 😉
 

Here I have shared it on my github: UdaraAlwis/XFForcefulKeyboardDismiss

Alright, happy coding fellas! 😀

Enjoy and Share!

-Udara Alwis

Setting RelativeLayout ConstraintExpressions from XAML Styles in Xamarin Forms…

When it comes to Xamarin Forms RelativeLayout we always use Constraints, its pretty easy to add those Constraint values from C# code behind, but when it comes to XAML UI implementation, it’s not so easy.

so myself…

I have been working with XAML UI implementation for the last year or so, specially dealing with a lot of pixel perfect design, which needs a lot of customization to design from XAML. But as a developer you have to find ways to deal with those stuff. In my current project we practice a strict discipline of MVVM pattern, which we strongly separate XAML UI View and the ViewModel code. So under no exceptions we add any single C# UI code or XAML code behind implementations in our project.

complex design implementations…

When you have to deal with complex design implementations in Xamarin Forms, the best way to go is with RelativeLayout, along with Relative Constraint values for X/Y position and Height/Width values.

flag1

RelativeLayout is good…

Usually those RelativeLayout Constraint values manages to get the job done, with ease on both Android and iOS devices. But sometimes it doesn’t quite go right, specially with Android, where you have to deal with different types of screen resolutions.

layouts1

but sometimes…

So at times like that you need to specify RelativeLayout ConstraintExpression separately for iOS and Android devices. But how do you do this in XAML code?

so how?

So how do you set those ConstraintExpression right from XAML code? Styles is the answer! 😀

The trick is to create two different Styles for Android and iOS, targeting the control you need to set the RelativeLayout Constraints on.

And then on your control’s XAML declaration, you set the Style property using the OnPlatform tag accordingly for iOS and Android.

Let’s do it…

You could define these Styles on your Page level or Application level as you wish as shown below…

You can see I have created twp styles which targets the Label control type and added my Relative Layout ConstraintExpressions. 🙂 Also I have added the other Properties that I need to customize through these Styles.

<ContentPage.Resources>
	<ResourceDictionary>
		<Style x:Key="MyLabelStyleiOS" TargetType="Label">
		  <Setter Property="BackgroundColor" Value="Yellow"/>
		  <Setter Property="HorizontalTextAlignment" Value="Center"/>
		  <Setter Property="RelativeLayout.YConstraint" 
				  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.5}"/>
		  <Setter Property="RelativeLayout.WidthConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
		  <Setter Property="RelativeLayout.XConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
		</Style>

		<Style x:Key="MyLabelStyleAndroid" TargetType="Label">     
		  <Setter Property="BackgroundColor" Value="Yellow"/>
		  <Setter Property="HorizontalTextAlignment" Value="Center"/>
		  <Setter Property="RelativeLayout.YConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.1}"/>
		  <Setter Property="RelativeLayout.WidthConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
		  <Setter Property="RelativeLayout.XConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
		</Style>
	</ResourceDictionary>
</ContentPage.Resources>

 

And then on the your Control that you need to set those RelativeLayout Constraints…

<Label Text="Welcome to the app!"  >
	<Label.Style>
	  <OnPlatform x:TypeArguments="Style"
				  iOS="{StaticResource MyLabelStyleiOS}"
				  Android="{StaticResource MyLabelStyleAndroid}" />
	</Label.Style>
</Label>

 

You can see how I have nested down the Style property and added the specific style according to the Platform type.

It’s very important to notice that I have added those Styles as StaticResource this is because we need to set those RelativeLayout ConstraintExpressions before the run time, while the XAML are being parsed. 🙂 Once the XAML layout is parsed, we can not set the ConstraintExpressions, since it’s not going to be rendered.

make it pretty… Generalize!

Yep the above styles are ugly, so let’s generalize it and move the common properties and constraints to a general style as below, and derive our child styles.

<Style x:Key="MyLabelStyle" TargetType="Label">
  <Setter Property="BackgroundColor" Value="Yellow"/>
  <Setter Property="HorizontalTextAlignment" Value="Center"/>
  <Setter Property="RelativeLayout.WidthConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
  <Setter Property="RelativeLayout.XConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
</Style>

<Style x:Key="MyLabelStyleiOS" TargetType="Label" BasedOn="{StaticResource MyLabelStyle}">
  <Setter Property="RelativeLayout.YConstraint" 
		  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.5}"/>
</Style>

<Style x:Key="MyLabelStyleAndroid" TargetType="Label" BasedOn="{StaticResource MyLabelStyle}">
  <Setter Property="RelativeLayout.YConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.1}"/>
</Style>

 

There we go! now that’s beautiful. Always keep in mind to generalize the common Style properties, and here in this case the common ConstraintExpression values. 🙂

Cheers! 😀

How to deal with Implementing an iOS optimized UI design on Android with Xamarin Forms?

When it comes to Cross-Platform mobile development, it is very crucial to have Screen Design concepts that are compatible for all the targeting platforms (Android/iOS/WinPhone), or at least to have separate Screen Designs for targeting platforms, when you’re using a platform such as Xamarin Forms (allowing you to develop apps with Native Look and Feels).

but…

What if you are out of luck in such requirements? What if as the developer you’re only given the Design Screens that only optimizes for one specific mobile platform?

and worst…

You’re expected implement the same design for both Android and iOS regardless of the design’s optimization?

my story…

Let me put it this way,

the project I’m currently working is a Cross-Platform Mobile Application building on top of Xamarin Forms. I am given a bunch of Design Screens that are optimized for iOS UI patterns, and my seniors wants me to implement the same UI Design for Android as well, regardless of the Android UI patterns.

So despite Xamarin Forms gives Native Look and Feels I am asked to implement the same design that are optimized for iOS into Android regardless of Android UX patterns.

Oh well.. look at that, so mostly to go against the Android UI Design best practices, just implement the iOS optimized design straightaway. (Well my UX Lead seems to be an iOS geek) 😛

Well this would have been better if we were developing on a Hybrid framework which uses HTML5 so that we could simply throw the same rendered result for both Android and iOS, but since its Xamarin Forms, which allows you to use Native Looks and Feels after compilation, it’s going to be a mess!

…gotta suck it up!

As the developer, I have no choice but to get this done somehow, even though the hell breaks loose! because it’s my JOB! 😛

Well for the User’s perspective, getting rid of the Android looks and feel, will surely disturb the User Experience on Android.

Challenges..

So as the developer, here are some challenges I faced…

Difference between iOS Designs VS Android Designs!

evasion-ios-71

When you take a iOS Mobile App design, its mostly a static UI design, which uses mostly pixel perfect and screen coordination perfect values for placing the components on the Screen. This is because for iOS devices almost all their devices uses a pre-defined common Screen-Size-Resolution or as in Screen Height-Width Ratio.

top-android-phones1

but when it comes to Android devices, there’s a massive sea of fragmented Screen Sizes, and according to researches it only keeps on growing, therefor for Android Mobile App Designs are compiled with non-static flexible UI Design, which has room to stretch and shrink accordingly as much as possible without disrupting the User Experience.

Dealing with the Android sea of Device…

Just to give you a head start take a look at the following illustration which shows the different Android screen sizes that are available in the market by 2016! :O

screen-shot-2014-08-21-at-1-49-11-pm-1280x748

So you have to deal with the completely unexpected screen-sizes and resolutions, when you try to implement an iOS optimized UI Design for Android. Because of the pure difference I mentioned earlier, how could you take a static pixel-perfect, component coordinates fixed design and adopt it and make it flexible for the massive sea of device fragmentation of Android? 😦

…but not giving up!

So as the job role of a Developer we are suppose to solve problems and accept whatever the challenge throws at us, even the hell breaks loose!

So this is how I resolved it with Xamarin Forms!

So how did I do it?

So let’s go through one by one!

1. RelativeLayout for ze rescue…

Yes that’s right, Xamarin Forms provides several types of Layout types for the ease of Developer and luckily they also provide a Layout called Relative Layout. And yes it does exactly from what it’s name shows.

layouts1

RelativeLayout is used to position and size views relative to properties of the layout or sibling views.

Unlike StackLayout and GridLayouts which most developers use in Xamarin Forms, for the ease of use, RelativeLayout allows you to place its Children Relatively to each other or for the parent view.

Therefore when dealing with different screen sizes of Android we could push the UI to render itself Relatively to given parameters while maintaining the expected UI design as much as possible.

Take a look at the below example from Xamarin docs:

flag1

As you can see, using this Layout we could implement and render the same Design across all mobile platforms. Hence we are placing all the components on the screen, RELATIVE to each other.

2. Always use Constraint type as RelativetoParent!

RelativeLayout provdes three types of Constraint type to place your Components inside the layout, that are

  • RelativeToParent: Set the value relatively to the ParentView
  • RelativeToView: Set the value relatively to another View in the same parent Layout
  • Constant: Set the value as a Constant value

So out of these three types, I would recommend always sticking to the RelativeToParent type, which allows you to have more compatibility towards Android screen sizes, because we are relying on the Parent View which takes up the whole screen Heigh/Width/X or Y properties. So its always better to take relative values accordingly to the Parent instead of another View in the same Parent Layout, which may or may not be behaving as we expect, but as of Parent view, we are sure of its layout.

3. Use XConstraints and YConstraints

Now you must remember how I was crying out loud about having to implement a pixel-perfect screen coordinates fixed design on Android. 😛

So we are going to implement the exact same concept but RELATIVELY!

So with RelativeLayout we can set the X Y locations of a component Relatively to the parent or another view, which helps you place the component on the screen without any worries since those values will get set relatively at the run time. Yep no more worries about those coordinates for Android! 😉

4. Do not use StackLayout or GridLayout inside RelativeLayout!

That’s correct do not use them inside the RelativeLayout and place your child components inside them. Which will lead to the same issue we tried to solve at he beginning, because those Child elements will adopt themselves accordingly to the Stack or Grid Layouts, not for the RelativeLayout. So if you can try to place your child components inside RelativeLayout directly by setting the X/Y/Width/ and Height constraints.

5. Avoid Constants and use Factor…

Yes, with Factor you can get the best suited value according to the ratio of the Relative property, whether its X, Y, Width or even Height! 🙂

And please, stop using Constants, unless you really wants to, because then you will be completely killing the purpose of using the RelativeLayout, hence we need to achieve fluid flexibility to render the iOS optimized design on Android with Xamarin Forms! 😉

6. Also you could use Absolute Layout!

This also does something similar but a little bit differently which could also be used in our situation.

AbsoluteLayout positions and sizes child elements proportional to its own size and position or by absolute values.

So there’s something to keep in mind as well. 😉

Something to keep in mind…

Usage of RelativeLayout is going to be very costly during the run time, takes a lot of processing power to render the UI due to its Relative behaviour of the measurements, meanwhile Jason Smith also recommends avoid using RelativeLayout and instead stick to StackLayouts and GridLayouts.

But unfortunately in order to deal with this kind of scenarios, you have to compromise something , not to mention disrupting the native User Experience of the app.

Conclusion

So that’s how deal with my situation when I was given a iOS Optimized mobile design to be implemented on Android with Xamarin Forms! 😀

Very well then, if anyone else has gotten into this situation, I hope this post has helped you in some way! 🙂

Cheers!

Welcome to ÇøŋfuzëÐ SøurcëÇødë Tech Innovations !

Welcome to the ignition of Tech Innovations in Sri Lanka. We are a Sri Lankan based company that focuses on Technological Innovations and pushing the the boundaries beyond the Imagination.

CoverPic1

 

I have always been extremely passionate about Innovation and Creativity, and as a result of that I used to invent new things using whatever I learned. Even back in School Days I used to develop new inventions and win awards at competitions. That drove me to University, while studying Software Engineering, I always used to build new software tools y my self in whatever the theory that we learned during lectures, whereas most of the time I got too obsessed and I went ahead learning everything by myself about any specific subject. 
I have always dreamed of solving real life problems through new inventions and ideas, which is still the force that drives me forward. So as a result of my passion towards innovations and experimentation, I happened be developing so many softwares and apps which I had published to the public market. This sparked me the idea of initiating a startup of my own which I could drive through my passion. So here it is, Ladies and Gentlemen, Welcome to  ÇøŋfuzëÐ SøurcëÇødë Tech Innovations !
– Udara Alwis a.k.a. [CODENAME : ÇøŋfuzëÐ SøurcëÇødë]

Connect with us on our official Facebook page from the below link,

ProfilePic1 qrcode (2)

We already have a series of ongoing Innovative Development Projects and below are some of them.

Windows Phone App Development

We have already developed and published a series of Innovative and Creative Windows Phone Applications and published on Microsoft Windows Store which has gotten over 160,000 downloads worldwide along with a rapidly growing user base.

Over 30 Windows Phone Apps published…

Over 160,000 Users Worldwide…

CoverPic2

As we go on forward we are hoping to keep on developing more and more Innovative Windows Phone mobile apps. Also we are offering services to the public and business, so if you are in need of developing a Windows Phone app for your Company or Business, contact us immediately.

You can view all our Windows Phone apps by from below link,

462x120_WP_Store_blk

 

Sri Lankan Newspaper Cartoons Project

Welcome to “Sri Lanka Newspaper Cartoons” project, A centralized portal for showcasing and viewing all Sri Lankan Newspaper Cartoons published across the web. How we do this ? We have hosted cloud servers that crawls throughout the web searching for Newspaper Cartoons using our unique Web Crawling technologies and algorithms, where we will capture them and present to you by streaming from those servers.

Slide1

http://srilankannewspapercartoons.tk/

We simply bring all the Sri Lankan Newspaper Cartoons that are published across the web to one place and let you access them in a very easy to use, friendly, interactive way. We bring an ultimate experience of viewing Sri Lankan Newspaper Cartoons. Stunning visuals, interactive user experience blended together along with a faster and easier access and look up. “Sri Lanka Newspaper Cartoons”, we are empowering talented Sri Lankan Cartoon Artists to showcase and reach more audience easily and quickly and for the User, we are bringing an ultimate experience to view all Sri Lankan Newspaper Cartoons published across web, right from your fingertips….

Our fully automated system that is running behind this project was able to fetch over 11,000 Sri Lankan Newspaper Cartoons, while making this project the Sri Lanka’s first ever Largest Sri Lankan Newspaper Cartoons collection ever created.

Over 11,000 Newspaper Cartoons…

We are also opened up for Advertisers to publish ads on this project’s website and mobile app which are being used by over 1000s of users worldwide…

2 6 5 7

Download the Windows Phone app of our Sri Lankan Newspaper Cartoons project –

 http://www.windowsphone.com/en-us/store/app/sri-lankan-cartoons/83bfab81-883d-421e-8aba-c621bf67aee8

Here are some of the special features that we are bring you…

  • View all the Sri Lankan Newspaper Cartoons that has ever been published in Newspaper from one single place as you wish…
  • Stay up to date with the latest Sri Lankan Newspaper Cartoons and you can even view the oldest Cartoons ever…
  • Like or Dislike and Rate every single Cartoon…
  • Add Keywords and Tags to Cartoons as you like..
  • Easily share Cartoons with your Social Networks…

Sri Lanka Newspaper Cartoons Gallery

 

So join with us for the ignition of the next step of Sri Lankan Newspaper Cartoons entertainment…

Sri Lankan Memes Book

Welcome to the first ever largest Sri Lankan Memes collection ! The most awesome place for Sri Lankan Memes ! (^_-) Join with us today…

http://srilankanmemes.com/

CoverPhoto3

So are you Bored at Home ? or Work ? 9gag much ? a Memes fan ?
Welcome to the first ever largest Sri Lankan Memes collection !
Join Sri Lankan Memes Book today for the most awesome Sri Lankan Memes entertainment…

Welcome to the epic Book of all the Sri Lankan Memes Published on Facebook with over 15,000 Memes encountering Thanks to our unique intelligent Web Crawlers executing on Cloud… We are still on Beta level.. Stay tuned for our Official Release ! (^_-)

Sri Lankan Memes Book brings you the most amazing experience you ever had with Sri Lankan Memes entertainment. Such as,

  • View all the best Memes on Facebook
  • Even the Latest Memes, Recent Memes, Older Memes, most Liked or Disliked Memes, most Viewed Memes and so on..
  • View all the Memes under your favorite Meme pages
  • Vote Your favorite Memes
  • Daily updates of all the best Memes on Facebook
  • Like or Dislike Memes as you wish
  • Easily Share on Facebook or Twitter
  • View the best, Sri Lankan funny videos on Youtube…

You can also Watch the most awesome funny Sri Lankan Videos on Youtube via Sri Lankan Memes Book TV !
http://srilankanmemes.com/View_MemeStream_TV.aspx

News1

 
Visit our official Website –
http://srilankanmemes.com/

Facebook –
https://www.facebook.com/SriLankanMemesBook

Google –
https://plus.google.com/115627309497218505361

You can Subscribe to our Mailing list to receive daily awesome Sri Lankan Memes right into your inbox – http://goo.gl/oF6rTA

logo-base-test

Please drop a Like to the page if you think its awesome 😀 ! This is the first time such an app has been developed, so your support is highly appreciated. Please share with your friends as much as possible. 🙂

We have also opened up for Advertisers to publish Ads and Banners on our website and the mobile application. Please contact us if you are interested…

I Was There Map

I Was There Map, allows you to view all the places you have visited and your Facebook Check-ins. You can view all the amazing information statistics you have never known about those places and your check-ins. You will be shown all the interesting information about You and those check-ins like no other.
This project was developed based on ASP .net and C#. We have developed by our own custom API to grab data from Facebook for each and every user upon their permissions. We have invented a couple of innovative Algorithms in order to generate the relational data and information regarding the user and their check-ins information.

I Was There Map

Please check out more information from the below link,

https://theconfuzedsourcecode.wordpress.com/2014/04/03/i-was-there-map-is-ready-to-blow-your-mind/

Your Friends Map

Using ‘Your Friends Map’ you can view all your Facebook friends locations and hometowns in the world map. And it shows you a full list of all the locations and hometowns of your friends separately along with the number of friends in each location. This project was developed based on ASP .net and C#, where as I have used my own Custom Facebook API for pulling and streaming data from Facebook by the user’s permissions when the log in to the App.

We have invented a series of innovative algorithms to process the data and produce information regarding the user and their Friends, to populate statistical relationships.

Capture3

Please check out more information from the below link,

https://theconfuzedsourcecode.wordpress.com/2013/12/02/your-friends-map-is-ready-for-you/

Sri Lankan Photography Project

This project brings all Sri Lankan Photography that are published on Facebook to a one place, giving an ultimate experience to the user. With “Sri Lankan Photography”, we are empowering talented Sri Lankan Photographers to reach more audience easily and quickly and for the User, we are bringing a stunning ultimate experience for you to view all Sri Lankan Photography published on Facebook, right from your fingertips. This app provides so many special features, such as facilities keep in touch with the user’s favorite photographers as they wish, instantly viewing all the photo albums published on their public pages. Sharing those photography with user’s friends immediately on demand.

FlipCycleTileLarge

Please go to this link to view the full Article of our Sri Lankan Photography Project,

https://theconfuzedsourcecode.wordpress.com/2014/09/27/project-sri-lankan-photography/

Mobile In-App Advertising Project (Phase 1)

We have launched a project where we are giving In-App Advertising facilities to Advertisers and Companies in a series of popular Mobile apps developed by ÇøŋfuzëÐ SøurcëÇødë Tech Innovations.

Untitled

 

Please go to this link to view the Full Article of this project –

https://theconfuzedsourcecode.wordpress.com/2014/10/20/ultimately-boost-your-marketing-campaign-with-mobile-in-app-advertising/

Undisclosed Projects (under development) –

Intelligent Data Mining App (based on Social Media) Framework

A framework to fetch public Social Media data and coming up with analytical information through data mining…

Lanka Tuk Tuk Services Project

A new way of thinking about three wheeler services in Sri Lanka… (Coming Soon)

Mobile In-App Advertising Platform

A mobile in-app advertising platform for Sri Lankans…

 

So thats a little heads up about ÇøŋfuzëРSøurcëÇødë Tech Innovations initiation. So if any of you are interested of being a partner or an investor we would be very grateful to have you.

Till next time everyone.. 🙂 Cheers !

https://www.facebook.com/296474577210450

CoverPic1

Having Windows Bootloader Issues ? Then here is best Solution ! ;)

Installed Windows 8 on your Windows 7 PC hoping to get it dual booted ? Unfortunately the Dual boot screen (boot loader screen) went missing ? :O
Or lets say you installed Windows 7 on your Windows 8 PC hoping for a dual boot ? 😛 Aaaand tadaa ! the boot screen is missing ? :O
Or even may be you are much like my self and tried to mess with the system’s boot loader settings and eventually screwed it up ? 😉

Very well then here is the solution. “EasyBCD” ! This is a small software tool which I used sometime back when I screwed up my boot loader settings. This small software was very useful and powerful I was able to recover my bootloader within minutes. And moreover its very easy to use as well. You don’t have to buy the whole software, you can register and try out the non-commercial version with almost all the features. So if you are facing any of those above catastrophes or any of the similar situations, then go ahead and try it out as it has helped me once. 😉

https://neosmart.net/EasyBCD/

https://neosmart.net/EasyBCD/

Cheers folks ! (^_^)

Do you think you know Hackers ?

Check this out, an awesome InforGraph about who Hackers truly are !

http://notes.fundersandfounders.com/post/50417296471/who-are-hackers-hackers-are-doers

You thought hackers are the weirdo criminals hiding behind PCs in dark rooms as the media describes ? ARE YOU FUCKING KIDDING ME ? (-____-)

We Hackers are Doers ! We redefine the Impossibility ! We invent ! Challenge the Odds ! We penetrate the maximum of our Creativity through our passion, Mind that you fool ! 😛