2

This post shows how to make SvgCachedImage act like a button. However, how to load SvgCachedImage into XamarinForm's ImageButton Source ?

My non-working code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SharedSvgSample"
             x:Class="SharedSvgSample.MainPage"
             xmlns:ffimageloadingsvg="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms">
    <StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
        <ImageButton
            x:Name="myButton"
            HeightRequest="200"
            Clicked="myButton_Clicked"
            WidthRequest="200" />
    </StackLayout>
</ContentPage>

Code-behind:

using FFImageLoading.Svg.Forms;
using System;
using Xamarin.Forms;

namespace SharedSvgSample
{
    public partial class MainPage : ContentPage
    {
        private bool _myButtonValue;
        private SvgImageSource _visibilityOn = null;
        private SvgImageSource _visibilityOff = null;

        public MainPage()
        {
            InitializeComponent();
            _visibilityOn = SvgImageSource.FromResource("SharedSvgSample.Resources.visibility_on.svg");
            _visibilityOn.VectorHeight = 100;
            _visibilityOn.VectorWidth = 100;

            _visibilityOff = SvgImageSource.FromResource("SharedSvgSample.Resources.visibility_off.svg");
            _visibilityOff.VectorHeight = 100;
            _visibilityOff.VectorWidth = 100;

            myButton.Source = _visibilityOff;   
        }

        private void myButton_Clicked(object sender, EventArgs e)
        {
            _myButtonValue = !_myButtonValue;
            myButton.Source = _myButtonValue ? _visibilityOn.ImageSource : _visibilityOff.ImageSource;
        }
    }
}
Jeson Martajaya
  • 6,996
  • 7
  • 54
  • 56

1 Answers1

1

Unluckily, Xamarin.Forms.Button only supports FileImageSource, so at the moment you can't just load an SVG into the Button Image.

However, you can just load the SVG image, and add the TapGestureRecognizer to simulate a Button.

Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45