Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms: Embed symbols in text

I'm currently evaluating Xamarin Forms as an alternative to our webbased HTML applications targeting mobile platforms.

Our applications often use graphical symbols embedded in paragraphs of text. The desired effect looks like this:

Example

Of course the text also has to be able to freely wrap around, including all the symbols. In HTML this is simply achieved like this:

<p>Sample text with <img src="sample.jpg"> embedded</p>

How can I achieve the same effect using Xamarin Forms? I already looked at FormattedStrings which allow formatting of subparagraphs of Labels, however they do not seem to allow embedding of images.

Also please note that the solution is required to support iOS, Android and Windows Phone 8.1 at least.

like image 443
Thomas Hilbert Avatar asked Jan 08 '16 23:01

Thomas Hilbert


1 Answers

Obviously being forced to use a WebView almost defeats the point of moving a HTML5 app to Xamarin!

In the Xamarin Forums a similar question has been asked: https://forums.xamarin.com/discussion/1649/text-with-image

To solve the problem Tomasz Cielecki cooked up some sample code here: https://gist.github.com/Cheesebaron/5034440

He then went onto blog about it here: http://blog.ostebaronen.dk/2013/02/adding-images-to-textview-and-edittext.html

<snip>

I started out with a super simple sample trying to get an Image shown in a TextView. I googled up some solutions and sure, Spannables allow using ImageSpan inside of them! There were nice samples and such, and I came up with this.

ImageSpan in TextView

//Load up your drawable.
var imageSpan = new ImageSpan(this, Resource.Drawable.Icon);
//Set the text of SpannableString from TextView
var spannableString = new SpannableString(textView.Text);
//Add image at end of string
spannableString.SetSpan(imageSpan, textView.Text.Length-1, textView.Text.Length, 0);

Easy, huh? And you can add loads of other Spans to the Spannable, such as StyleSpan, which you can style your fonts with bold, italic and other styles.

Since that was so easy, I quickly tried to do that with an EditText. It also works just fine...

</snip>

like image 52
Jeremy Thompson Avatar answered Sep 28 '22 08:09

Jeremy Thompson