如何从另一个命名空间调用方法并传递数据

How can I call a method from another namespace and pass data

我想传递一个 SKImage 和一个字符串文件名来将图片保存到 phone 的目录。

我要调用的方法:

namespace LevelMeter.Droid
{
    public class SaveImage_Droid : SaveImage
    {
        public SaveImage_Droid(SKImage snapshot, string fileName)
        {
            SaveImage(snapshot, fileName);
        }

        public void SaveImage(SKImage snapshot, string fileName)
        {
            var pictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath;

            Bitmap bm = snapshot.ToBitmap();

            var filePath = System.IO.Path.Combine(pictures, fileName);
            var stream = new FileStream(filePath, FileMode.Create);
            bm.Compress(Bitmap.CompressFormat.Jpeg, 90, stream);
            stream.Flush();
            stream.Close();
        }
    }
}

我做了这个界面:

namespace LevelMeter
{
    public interface SaveImage
    {
        void SaveImage(SKImage snapshot, string fileName);
    }
}

我想从

调用它
namespace LevelMeter.Views
{
    public void SaveButton_Clicked(object sender, EventArgs e)
    {
        SKImage snapshot = surface.Snapshot();
        string fileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
        SaveImage(snapshot, fileName); //I cant't reach it
    }
}

您可以使用 DependencyService 从共享项目调用方法到 .Android 项目:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

    }

    public void SaveButton_Clicked(object sender, EventArgs e)
    {
        SKImage snapshot = surface.Snapshot();
        string fileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";

        DependencyService.Get<ISaveImage>().SaveImage(snapshot, fileName);
    }
}

public interface ISaveImage
{
    void SaveImage(SKImage snapshot, string fileName);
}

然后在Android项目中注册:Registration by attribute

[assembly: Dependency(typeof(SaveImage_Droid))]
namespace LevelMeter.Droid
{
    public class SaveImage_Droid : SaveImage
    {
        public SaveImage_Droid(SKImage snapshot, string fileName)
        {
            SaveImage(snapshot, fileName);
        }

        public void SaveImage(SKImage snapshot, string fileName)
        {
            var pictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath;

            Bitmap bm = snapshot.ToBitmap();

            var filePath = System.IO.Path.Combine(pictures, fileName);
            var stream = new FileStream(filePath, FileMode.Create);
            bm.Compress(Bitmap.CompressFormat.Jpeg, 90, stream);
            stream.Flush();
            stream.Close();
        }
    }
}