Xamarin.Controls.Signaturepad.Forms返回黑色图像

时间:2019-01-07 00:16:18

标签: xamarin xamarin.forms xamarin.android

我的签名板有问题。我正在将图像保存到设备中,但仅返回黑色图像。我该如何解决?我下面的代码是保存流中的签名

Stream sigimage = await Signature.GetImageStreamAsync(SignaturePad.Forms.SignatureImageFormat.Png);

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), signatureFile);

using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
   await sigimage.CopyToAsync(fileStream);
}

1 个答案:

答案 0 :(得分:0)

首先,如果您安装了正确的软件包,如以下屏幕截图所示。 enter image description here

然后,在保存此图像之前,是否保存了矢量(Points of signatureView)?

这是有关情况的演示。演示首先保存矢量,然后保存图像,最后加载图像。您可以参考它。

enter image description here 这是Eventpage的代码,您可以参考它。

EventsPage.xaml

<?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:controls="clr-namespace:SignaturePad.Forms;assembly=SignaturePad.Forms"

         x:Class="SignatureDemo.EventsPage"

          Title="Events">

<Grid x:Name="LayoutRoot" Padding="12">



    <Grid.RowDefinitions>

        <RowDefinition Height="*" />

        <RowDefinition Height="12" />

        <RowDefinition Height="Auto" />

    </Grid.RowDefinitions>



    <ContentView Padding="1" BackgroundColor="#B8860B">

        <controls:SignaturePadView

            x:Name="signatureView" StrokeCompleted="SignatureChanged" Cleared="SignatureChanged"

            CaptionTextColor="#B8860B" ClearTextColor="#B8860B" PromptTextColor="#B8860B"

            SignatureLineColor="#B8860B" BackgroundColor="#FAFAD2" />

    </ContentView>



    <Button

        x:Name="btnSave" Text="Save Vector" Clicked="SaveVectorClicked"

        HorizontalOptions="Start" VerticalOptions="End" Grid.Row="2" />



    <Button

        x:Name="btnLoad" Text="Load Vector" Clicked="LoadVectorClicked"

        HorizontalOptions="Center" VerticalOptions="End" Grid.Row="2" />



    <Button

        x:Name="btnSaveImage" Text="Save Image" Clicked="SaveImageClicked"

        HorizontalOptions="End" VerticalOptions="End" Grid.Row="2" />



</Grid>

</ContentPage>

EventsPage.xaml.cs

 namespace SignatureDemo

{

public partial class EventsPage : ContentPage

{

    private Point[] points;



    public EventsPage()

    {

        InitializeComponent();



        UpdateControls();

    }



    private void UpdateControls()

    {

        btnSave.IsEnabled = !signatureView.IsBlank;

        btnSaveImage.IsEnabled = !signatureView.IsBlank;

        btnLoad.IsEnabled = points != null;

    }



    private void SaveVectorClicked(object sender, EventArgs e)

    {

        points = signatureView.Points.ToArray();

        UpdateControls();



        DisplayAlert("Signature Pad", "Vector signature saved to memory.", "OK");

    }



    private void LoadVectorClicked(object sender, EventArgs e)

    {

        signatureView.Points = points;

    }



    private async void SaveImageClicked(object sender, EventArgs e)

    {

        bool saved;

        using (var bitmap = await signatureView.GetImageStreamAsync(SignatureImageFormat.Png, Color.Black, Color.White, 1f))

        {

            saved = await App.SaveSignature(bitmap, "signature.png");

        }



        if (saved)

            await DisplayAlert("Signature Pad", "Raster signature saved to the photo library.", "OK");

        else

            await DisplayAlert("Signature Pad", "There was an error saving the signature.", "OK");

    }



    private void SignatureChanged(object sender, EventArgs e)

    {

        UpdateControls();

    }

}

}

App.xaml.cs

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]

namespace SignatureDemo

{

public partial class App : Application

{

    private readonly Func<Stream, string, Task<bool>> saveSignatureDelegate;



    public App(Func<Stream, string, Task<bool>> saveSignature)

    {

        InitializeComponent();



        saveSignatureDelegate = saveSignature;



        MainPage = new NavigationPage(new MainPage());

    }

    public static Task<bool> SaveSignature(Stream bitmap, string filename)

    {

        return ((App)Application.Current).saveSignatureDelegate(bitmap, filename);

    }



 }

}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"

         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

         xmlns:local="clr-namespace:SignatureDemo"

         x:Class="SignatureDemo.MainPage"

         Title="Signature Pad">



   <local:EventsPage Title="Events" />

 </TabbedPage>

MainPage.xaml.cs

namespace SignatureDemo

{

  public partial class MainPage : TabbedPage

  {

      public MainPage()

      {

          InitializeComponent();

      }

    }

}

MainActivity.cs在Android中

namespace SignatureDemo.Droid

{

[Activity(Label = "SignatureDemo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity

{

    protected override void OnCreate(Bundle savedInstanceState)

    {

        TabLayoutResource = Resource.Layout.Tabbar;

        ToolbarResource = Resource.Layout.Toolbar;



        base.OnCreate(savedInstanceState);

        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        LoadApplication(new App(OnSaveSignature));

    }

    private async Task<bool> OnSaveSignature(Stream bitmap, string filename)

    {

        var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures).AbsolutePath;

        var file = Path.Combine(path, "signature.png");



        using (var dest = File.OpenWrite(file))

        {

            await bitmap.CopyToAsync(dest);

        }



        return true;

    }

   }

  }

不要忘记在AndroidManifest.xml中授予以下权限。

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

AppDelegate.cs

namespace SignatureDemo.iOS

{

// The UIApplicationDelegate for the application. This class is responsible for launching the 

// User Interface of the application, as well as listening (and optionally responding) to 

// application events from iOS.

[Register("AppDelegate")]

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate

{

    //

    // This method is invoked when the application has loaded and is ready to run. In this 

    // method you should instantiate the window, load the UI into it and then make the window

    // visible.

    //

    // You have 17 seconds to return from this method, or iOS will terminate your application.

    //

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)

    {

        global::Xamarin.Forms.Forms.Init();

        LoadApplication(new App(OnSaveSignature));



        return base.FinishedLaunching(app, options);

    }

    private async Task<bool> OnSaveSignature(Stream bitmap, string filename)

    {

        var tcs = new TaskCompletionSource<bool>();



        UIImage image;

        using (var data = NSData.FromStream(bitmap))

        {

            image = UIImage.LoadFromData(data);

        }



        var status = await PHPhotoLibrary.RequestAuthorizationAsync();

        if (status == PHAuthorizationStatus.Authorized)

        {

            image.SaveToPhotosAlbum((i, error) =>

            {

                image.Dispose();



                tcs.TrySetResult(error == null);

            });

        }

        else

        {

            tcs.TrySetResult(false);

        }



        return await tcs.Task;

    }

}

}