Taoffi's blog

prisonniers du temps

Xamarin forms – the complete WP circle image!

James Montemagno published a post about implementing circle images using Xamarin Forms.

His proposed implementation for Win Phone was good. It clipped the image into a circle, but stopped a little short to draw the circle image border.

 

Droid

WP

 

I played with this to solve this small issue.

Here is a more complete version for WP renderer:

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
	base.OnElementPropertyChanged(sender, e);

	CircleImage		circleImg	= Element as CircleImage;

	if(circleImg == null || Control == null || Control.Clip != null || circleImg.Source == null)
		return;
			
	double		controlRadius	= Math.Min(Element.Width, Element.Height) / 2.0f;
	double		controlDiameter	= controlRadius * 2.0;

	if(controlRadius <= 0)
		return;


	// **********************************************
	// Note: this section ignores PNG transparency. 
	// **********************************************
	try
	{ 
		BitmapImage			srcBmp		= Control.Source as BitmapImage;

		WriteableBitmap		wrBmpSrc	= new WriteableBitmap((int) controlDiameter,
												 (int) controlDiameter);
		ImageBrush		imgBrush	= new ImageBrush();

		// use an image brush with the control’s image
		imgBrush.ImageSource = srcBmp;

		// set border thickness
		int	borderThickness	= circleImg.BorderThickness;
		Color	borderColor			= XamarinColor2WinColor(circleImg.BorderColor);

		// create a path with an ellipse geometry
		EllipseGeometry				ellipseG	= new EllipseGeometry()
			{
				Center		= new System.Windows.Point(controlRadius, controlRadius),
				RadiusX		= controlRadius,
				RadiusY		= controlRadius
			};
		GeometryGroup				geomGroup	= new GeometryGroup();

		geomGroup.Children.Add(ellipseG);

		System.Windows.Shapes.Path	path		= new System.Windows.Shapes.Path()
		{
			Stroke 		= new SolidColorBrush(borderColor),
			StrokeThickness	= borderThickness,
			Data			= geomGroup,
			Width			= controlDiameter,
			Height		= controlDiameter,
			Fill			= imgBrush,
		};

		wrBmpSrc.Render(path, null);
		wrBmpSrc.Invalidate();

		using (MemoryStream memStream = new MemoryStream())
		{
			wrBmpSrc.SaveJpeg(memStream, wrBmpSrc.PixelWidth, wrBmpSrc.PixelHeight, 0, 100);

			srcBmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;

			srcBmp = new BitmapImage();
			srcBmp.SetSource(memStream);
		}

		Control.Source			= srcBmp;
	}
	catch(Exception ex)
	{
		Debug.WriteLine(ex.Message);
		return;
	}

	// clip the control into circle
	Control.Clip = new EllipseGeometry
		{
			Center	= new System.Windows.Point(controlRadius, controlRadius),
			RadiusX	= Math.Max(controlRadius, 0),
			RadiusY	= Math.Max(controlRadius, 0)
		};
}

 

 

Color conversion helper method

 

		public static Color XamarinColor2WinColor(Xamarin.Forms.Color xamColor)
		{
			return Color.FromArgb (	(byte)(xamColor.A * 255),
									(byte)(xamColor.R * 255),
									(byte)(xamColor.G * 255),
									(byte)(xamColor.B * 255));
		}

 

 

 

Droid

WP

 

Xamarin forms fonts: Handling droid formatted text spans

As we have seen in a previous post, it is relatively easy to handle custom fonts using Xamarin forms. The only tedious platform in this domain is Android where you need to write a custom renderer.

In the first version of Droid custom renderer, I didn't handle the Labels Formatted Text.

Formatted texts can be used like in this sample:

 

<Label>
    <Label.FormattedText>
        <FormattedString>
            <FormattedString.Spans>
                <Span
                    Text="Allura span"
                    ForegroundColor="Lime"
                    FontSize="36"
                    FontFamily="{StaticResource fontAlluraName}"
                    />
                <Span
                    Text=" "
                    FontSize="{StaticResource awesomeSize}"
                    ForegroundColor="Lime"
                    FontFamily="{StaticResource fontawsomeName}"
                   />
           </FormattedString.Spans>
        </FormattedString>
    </Label.FormattedText>
</Label>



 

That is a Droid-only problem!

In Windows Phone and iOS, once the fonts have been included in the project, you have nothing to do. The problem is with the Droid custom renderer!

Android has a font Typeface which acts on the Label globally, and another Type 'TypefaceSpan' which acts on a region (span) of the label's formatted text.

In the first version of Droid renderer sample, we have set the font TypeFace for the label. If that label contained formatted text with spans, they were simply ignored (rendered with a default system font).

 

TypefaceSpan (namespace Android.Text.Style in Mono.Android.dll) is a class derived from à CharacterStyle whose role is to draw a span's text with the specified font family name.

 

A solution

After searching the Internet for a while, the question didn't seem to have many people talking about.

Luckily, I fall on a piece of code (a secretJ) where I found a link about an awesome solution proposed in this page.

In fact, you may derive a class based on TypefaceSpan, and override its methods according to your specific information (notably the span's font and its attributes).

 

A Label object has a FormattedText member which may contain one or more text Spans. Each span has a set of properties of which you find the font family (and font attributes) to be applied to the span's text.

So that now becomes manageable: your derived CustomTypefaceSpan can then create the font and draws the span's text accordingly.

 

 

 

The updated version of the sample code contains more details. Have fun doing more additions… would be nice to keep me posted!

 

Xamarin forms: What is my (current) app version?

Knowing which version of our application is currently running is a useful information (for end user, but also for us, developers!)

Fortunately, as Xamarin Forms is a .NET framework, we can easily obtain this at runtime:

public string AppVersion
{

    get
    {
        Assembly        asm        = this.GetType().GetTypeInfo().Assembly;
        string        name        = iAssemblyInfo.GetAssemblyTitle(asm),
                        copyright    = iAssemblyInfo.GetAssemblyCopyright(asm);

            return name + "\n" + copyright + "\n" + asm.FullName;
    }
}

 

Some details: this (somehow concise) code benefits of a helper static class that may give you some ideas:

 

  publicstaticclass iAssemblyInfo

 

 

The class exposes several methods like:

public static string GetAssemblyCopyright(Assembly asm)
{
    if(asm == null)
        return "";

    try
    {
        var        attrib    = asm.GetCustomAttribute<AssemblyCopyrightAttribute>();

        return attrib == null ? "" : attrib.Copyright;
    }
    catch (Exception)
    {
        return "";
    }
}

 

public static string GetAssemblyTitle(Assembly asm)
{
    if(asm == null)
        return "";

    try
    {
        var        attrib    = asm.GetCustomAttribute<AssemblyTitleAttribute>();

        return attrib == null ? "" : attrib.Title;
    }
    catch (Exception)
    {
        return "";
    }
}

 

public static string GetAssemblyCompanyName(Assembly asm)
{
    if(asm == null)
        return "";

    try
    {
        var        attrib    = asm.GetCustomAttribute<AssemblyCompanyAttribute>();

        return attrib == null ? "" : attrib.Company;
    }
    catch (Exception)
    {
        return "";
    }
}

Xamarin forms: a radio button pause!

 

Check boxes and Radio buttons are two UI elements frequently used in many apps.

In Xamarin forms those two (standard) items seem to create so many discussions without really getting a final answer. Many approaches go through 'custom renderers'… and I finally dislike this. That is simply because it questions the very reason why we use Xamarin forms itself. If everyone is going to create 'custom renderers' for such standard controls, it may become useless for XF to evolve providing new standard renderers… and there will be fewer reasons to use XF (see this post).

Like for Buttons (see this post), I think a check box or radio button can be defined as a surface containing graphical shapes (and animations) to represent the state of a property. In the case of such buttons: Checked/Unchecked state (a simple Boolean).

 

Waiting for XF to bring us a 'standard' check box and radio button, we have to manufacture them ourselves in the less costly possible way: avoiding custom renderers (again: because custom renderers will, one day, conflict with XF standard renderers)

 

The case of radio buttons is more interesting for an example because the selected (checked) option is exclusive: it should automatically uncheck all other options of one same group.

There is an interesting sample here. The only thing is that it again uses custom renderers where I think we don't need them.

To illustrate this in a simple way: a radio button can be checked:

Or unchecked:

All what we need is to select the image (or path… or whatever graphical shape) related to the current option state.

Naturally, this graphical element is accompanied by a Label (or image…) which describe the related option.

As you will see in the sample code, there is much more work to represent the Option's state objects than the graphical UI part that represents this state!

The radio button control (ContentView)

The radio button control (ContentView) may look like this:

  • A grid with two column cells
  • The left cell contains the two images of the option states checked/unchecked. One of them is hidden (according to current option state).
  • The right cell contains the description of the option (here: a Label)

 

<ContentView.Content>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="28" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <Image x:Name="imgUnselected" />
        <Image x:Name="imgSelected" IsVisible="{Binding IsSelected}" />
        <Label Grid.Column="1" Text="{Binding Label}"/>
    </Grid>
</ContentView.Content>


To show this simple control in action, we have to create some objects to represent the option group object and the option object.

 

  • ISelectable Interface defines the elementary option
    Note: the ISelectable (wording and Interface) have been borrowed from this interesting blog: Adventure in Xamarin Forms.
  • IExclusiveOptionSet is a template collection of ISelectable options which, in the same time, implements the ISelectableExclusiveSet Interface (see below)

 

public abstract class iExclusiveOptionSet<T> : XObjectListNotifier<T>, ISelectableExclusiveSet
                        whereT : ISelectable

 

  • XObjectListNotifier<T> list template is a root collection responsible of notifying collection changes (please see the sample code for more information)
  • The ISelectableExclusiveSet Interface is defined as:

 

public interface ISelectableExclusiveSet
{
    string        Label                { get; set; }
    ISelectable    SelectedItem    { get; set; }
}

 

  • Finally, for this sample, a demo (singleton) class provides some options to demo:

 

iOptionGroup _sampleOptionGroup    = new iOptionGroup("Sample option group");

 

_sampleOptionGroup.Add(new iOption(){ Id = 1, Label = "Sample option 1", IsSelected = true });
_sampleOptionGroup.Add(new iOption(){ Id = 2, Label = "Sample option 2", IsSelected = false });
_sampleOptionGroup.Add(new iOption(){ Id = 3, Label = "Sample option 3", IsSelected = false });
_sampleOptionGroup.Add(new iOption(){ Id = 4, Label = "Sample option 4", IsSelected = false });

 

  • An Option group control contains a stack layout. At the OnBindingContextChanged event, the stack layout is filled with the options of the received IEnumerable<iOption> collection.

 

protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();

    this.panelItems.Children.Clear();

    var optionList = this.BindingContext as IEnumerable<iOption>;

    if (optionList == null)
        return;

    foreach(var item in optionList)
    {
        RadioButtonCtrl    ctrl    = new RadioButtonCtrl(_isReadOnly)
        {
            BindingContext        = item,
            VerticalOptions        = LayoutOptions.Start,
            HorizontalOptions    = LayoutOptions.FillAndExpand
        };

        this.panelItems.Children.Add( ctrl);
    }
}


You may download the sample code here. Have fun adding animation, colors… I promise to submit this to my friends @UXDivers… you will probably see something much more elaborate later if they find this of interest!

 

 

Xamarin forms: Traversing the View tree

 

It is sometimes necessary to find the parent of a View element.

Imagine you have a navigation control (a menu for instance) in which each button gives access to a specific page.

What if the target page is the current displayed one? (If a copy of this navigation control is, for instance, inserted inside this same page)

It would be useless (and maybe rather ugly, confusing and probably troublesome!) to try to display (push) the current page on itself.

In that case, it would be good to know if one of the ascendants of the control is this target page before trying to do the navigation.

A simple helper method can do this for us:

//
// Try to find an ascendant (parent) of type T
public static T GetParentPage<T>(View control) where T : ContentPage
{
    if(control == null)
        return null;

    var        parent    = control.Parent;

    while(parent != null)
    {
        if(parent is T)
            return parent as T;

        parent = parent.Parent;
    }
    return null;
}


Usage example:

 

//
var currentPage = UiHelpers.GetParentPage<CompanyPage>(this);

// It is alreay on screen: do nothing
if(currentPage != null)
    return;

// push a new page
await Navigation.PushAsync(new CompanyPage())

 

Searching a descendant is a little trickier… because one same page may contain several instances of one same ContentView (control). Combined with a specific BindingContext, that can be more effective. Something like:

//
public static T GetChildCntrol<T>(View control, object BindindingContext) where T : ContentView

 

You may try to play with this… Good luckJ

Xamarin forms: avoid using string constants in NotifyPropertyChanged

 

As you know, notifying property changes is an essential pattern for Bindings to work as expected on xaml UI controls. Solution objects that are related to the UI (at least those of the 'VM' in: MV[VM]) should implement the INotifyPropertyChanged Interface. That is: expose a PropertyChanged event (of Type PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)).

Property changes consequently raise this event for any subscriber to be notified of the change.

The PropertyChangedEventArgs sent to the subscriber contains the changed property name.

So, for instance, if you change a property named BirthDate:

public DateTime BirthDate
{
    get { return _birthdate; }
    set
    {
        _birthdate = value;
        OnPropertyChanged("BrirthDate");
    }
}

One known issue is that when you change the property name, you may forget changing the name used in the change notification. And that, of course, produces unexpected behaviors that may be difficult to track.

A solution I use to avoid this (don't remember where I did found it!), is using System.Linq.Expressions to write something similar to this:

 

// Note: TProperty is the calling property Type 
protected void NotifyPropertyChanged<TProperty>(Expression<Func<TProperty>> property) 
{
    var expression     = property.Body as MemberExpression; 
    if (expression == null || expression.Member == null) 
        return; 
    string name        = expression.Member.Name;

    OnPropertyChanged(name); 
}

And that would allow us to avoid using string constants for property names… like in:

 

public DateTime BirthDate
{
    get { return _birthdate; }
    set
    {
        _birthdate = value;
        NotifyPropertyChanged(() => BrirthDate);
    }
}

 

 

Xamarin forms: Did you say Buttons?

 

Buttons are still the traditional elements through which the user interacts with software features.

With the mobile environment development context (dimensions, touch screen, gestures…) buttons became graphical parts that have to indicate a metaphor of the feature they give access to.

So, no surprise, many developers ask how to customize buttons to achieve this: using colors, images, symbols… etc.

The Xamarin Forms Button object

Like many other buttons, Xamarin forms button is far from able to satisfy this metaphoric aspects needed by modern mobile developers.

It represents a simple (rather poor) set of properties and leaves the developer out of intuitively finding a modern choice. You just have: Border, Font, Text…

It exposes a property Image… prowess?J… Not so fast, this property is simply defined as: Gets or sets the optional image source to display next to the text in the Button. (Faire enough!)

 

What is a Button?

After struggling sometime to find a way for 'customizing' buttons, we can just stop and ask ourselves this question. Yes, let us forget object libraries and just ask: What is a button?

As far as I know, it is a surface containing some graphic shapes… and, when clicked executes a command.

When tapped, the button produces a visual effect to mimic the reaction of a real life button.

 

Well, that now seems easy to build.

 

It can simply be a ContentView on which we may put whatever graphic elements we need (multiline texts, images… etc.). When clicked it plays an animation to mimic the press effect, and it then executes the command of our choice.

For this control to be reusable, we may expose properties needed for setting the graphic content and for handling the Click event as the developer may need.

 

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x
="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class
="iButton.iButtonCtrl" BackgroundColor="Gray">
<Frame x:Name="buttonFrame" HasShadow="False" OutlineColor="Black" />
</ContentView>

In the code behind, we expose the Content of our buttonFrame to be set with any ContentView we may find useful to use:

 

 

public ContentView ButtonContent 
{ 
    get { return this.buttonFrame.Content; } 
    set {    this.buttonFrame.Content    = value; } 
}

 

We define a Tap gesture recognizer to play the press graphical effect and raise a Clicked event to be handled by our control user.

public event ClickedHandler        ControlClicked;
ICommand    _tapCommand;

public ICommand WidgetTapped 
{ 
    get
    { 
        if(_tapCommand == null) 
        { 
            _tapCommand = new Command(async(obj) => 
            { 
               // play a press animation
                await Blink(this, 300);

                // someone subscribed to our event?: notify him
                if (ControlClicked != null) 
                    ControlClicked.Invoke(this, new EventArgs()); 
            }); 
        } 
 
        return _tapCommand; 
    } 
}

 

We can now create buttons the way we like or find useful… example:

First we include a reference to the button namespace:

    xmlns:ctrls="clr-namespace:iButton;assembly=iButton"
 

Then we can go ahead and create our buttons:

 

<StackLayoutSpacing="20"HorizontalOptions="FillAndExpand"Padding="10" >
   <ctrls:iButtonCtrlx:Name="ibutton1"BackgroundColor="#ffff9800" />
   <ctrls:iButtonCtrlx:Name="ibutton2" />
   <ctrls:iButtonCtrlx:Name="ibutton3"BackgroundColor="#ffcac8ff"/>
</StackLayout>

We insert the ContentViews we need for each button:

this.ibutton1.ButtonContent    = new iButtonView1(); 
this.ibutton2.ButtonContent    = new iButtonView2(); 
this.ibutton3.ButtonContent    = new iButtonView3(); 

// we subscribe to the Click event

ibutton1.ControlClicked += Ibutton1_ControlClicked;

 

 

 

 

Final professional touch: xaml markup extensions!

In order for people using this control to be able to use our button properties inside xaml files, we need to declare a bindable property that gives access to our: ButtonContent.

 

The sample code contains such final touches!

Xamarin forms: Don’t do modal (useless)

 

A vestige of old desktop applications UI is what is called: Modal Dialogs.

By 'Modal' we meant a 'sans-issue' place. A place where I put my user in a situation where he or she cannot go further before providing an information!

An investigation cell / A Quarantine / A Guantanamo Bay in some ways. Where I (the app developer or architect) feel secure and menacing (while pretending doing this for the end user's benefit!)… Did you say schizophrenia? :)

 

In those old days, that was an easy way for a developer to ensure the integrity of a workflow for certain key steps.

Was that wrong? Surely Yes. But lacking the means to construct an acceptable workflow integrity mechanism that can now be excusable (or forgiven).

I mean: if a workflow step may execute while it requires a previous validation that did not complete. That is entirely imputable to the application and cannot be the end user's fault.

If accessing a bank account page requires login, it is the bank account page responsibility to check if there is someone logged-in and authorized to view it (Whether we displayed a Login page or not). The fact that the Login page can be 'modal' may have a simple symbolic meaning, but at a functional level there is no sense to keep the user locked on this page or prevent him or her from doing something else (let only: cancelling!).

 

With the time going, this 'modal' vestige has proved more and more ineffective and often ridiculous. In an Internet app for instance, you cannot lock me on a modal page. I may navigate somewhere else… duplicate the navigator's tab… open another navigator, or close all and go for a beer!

In the mobile apps world that has even less sense. A mobile developer who might like these 'modal' patterns would find himself in a real battle against windmills.

 

Xamarin Forms supply a Navigation.PushModal / PopModal. But that has little sense though. Currently, the 'modal' pattern is not (at all) effective on Win Phone. In iOS, using modals often generates weird navigation situations and errors (many questions about this subject on various forums since 2014… without a final or accurate answer). In Android, modal navigation works nearly as expected, except that the OS (or the device) provides a 'back' button that allows anyone to easily exit the 'modal' prison we created for him or her!

 

So if you don't want to lose your time building strange and useless fences to keep your users in 'modal' prison cells, please don't use those Modal Push / Pop. Keep the navigation 'natural' as it is proposed by the OS. And invest more time for ensuring each step has its self-integrity mechanisms. That is a more reasonable approach.

 

Finally, we sometimes confuse 'modal' and 'full-screen' page. If you need your page to be full-screen (without the top navigation bar) that is quite easy in Xamarin Forms. Just insert this in your navigation page's constructor:

NavigationPage.SetHasNavigationBar(this, false);

Xamarin forms: Access your app resources in code

 

 

We now know how to create an App.xaml file (see this post) to define application resources.

To access these resources in xaml, we simply use {StaticResource yourResourceKey} or {DynamicResource yourResourceKey} (you can know more about StaticResource and DynamicResource, and which one to choose Here)

 

Still so often you need to access these resources in your code and that is quite simple:

You may define a static helper that can do this whenever needed:

 

public static object FindResource(string resourceKey)
{
    if(string.IsNullOrEmpty(resourceKey))
        return null;

        return Application.Current.Resources.FirstOrDefault(r => r.Key == resourceKey);
}

 

Now, you can more easily get an application resource by its key.

Let us also write a similar method that can extract this type of resource according to the OS on which the application is running using defined OnPlatform resource:

 

First a generic method that returns a per-Type OnPlatform value:

 

public static T GetPlatformValue<T>(OnPlatform<T> onplatformObjects) where T : class
{
    TargetPlatform    currentOs    = Device.OS;
    T            obj    = onplatformObjects == null
                            ? null
                            : currentOs == TargetPlatform.Android
                                ? onplatformObjects.Android
                                    : currentOs == TargetPlatform.iOS
                                        ? onplatformObjects.iOS
                                            : onplatformObjects.WinPhone;
    return obj;

}

 

Now, to get a device-dependent string defined in an OnPlatform resource with a specified key, we can write:

 

 

public static string FindOnPlatFormStringResource(string resourceKey)
{
    return (string.IsNullOrEmpty(resourceKey)) ? null
                : GetPlatformValue<string>(FindResource(resourceKey)
                    as OnPlatform<string>);
}

 

Putting these helper methods inside a static helper class would be a good thing (for all projects)!

Xamarin forms: five minutes pause!

Flood Fill a droll control

With Xamarin, you also have time to play!

Here I tried to play with a .png image file combined with a BoxView.

The .png file has some (transparent) holes…

With a BoxView (placed behind the image) and grows filling up the holes using the Animate method

 

<Grid x:Name="mainGrid" Padding="8" >
<Grid.RowDefinitions>
<RowDefinition Height="78" />
<RowDefinition Height="333" />
</Grid.RowDefinitions>

<Button x:Name="buttonStart" Grid.Row="0" Text="Start"
BorderRadius="20" HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand" />

<BoxView x:Name="floodBox" Grid.Row="1" HeightRequest="0.1"
HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand"
BackgroundColor="Fuchsia" />
<Image x:Name="img" Grid.Row="1" Source="{StaticResource imageFile}"
Aspect="AspectFill" HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
</Grid>

 

On button clicked, we start the animation:

 

private void ButtonStart_Clicked(object sender, EventArgs e)
{
    buttonStart.IsEnabled    = false;    // disable the button during animation

    double        height    = this.img.Height;

    floodBox.Animate("flood",
(percent) =>
    {
        floodBox.HeightRequest    = height * percent;

    }, 16, 10000, Easing.Linear,

// re-enable the button at animation end
(d1, d2) => buttonStart.IsEnabled = true);
}

 

 

If you would like to play with other images / animations… here is the code!