Xamarin.forms导航另一页后如何在同一页上保留图像 [英] Xamarin.forms how to hold image on same page after navigating another page

查看:107
本文介绍了Xamarin.forms导航另一页后如何在同一页上保留图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在个人资料页面上上传了图片,并且我希望保留该图片,直到我以xamarin形式注销.

I have uploaded image on my profile page and I want to hold that image until I logout in xamarin forms.

如果我选择其他页面,我的图像将会丢失,因此我想保留它直到注销.

My image will be lost if I select another page so I want to hold it until I log out.

var profile = new Image { };
profile.Source = "profile.png";
profile.HorizontalOptions = LayoutOptions.StartAndExpand;
profile.VerticalOptions = LayoutOptions.StartAndExpand;

var profiletap = new TapGestureRecognizer();

profiletap.Tapped += async (s, e) =>
{
    var file = await CrossMedia.Current.PickPhotoAsync();
    if (file == null)
        return;
    await DisplayAlert("File Location", file.Path, "OK");

    im = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        //file.Dispose();
        return stream;
    });

    profile.Source = im;

//   await Navigation.PushModalAsync(new PhotoPage(im));
};

profile.GestureRecognizers.Add(profiletap);

推荐答案

导航到另一个页面并返回时页面不会被破坏,这就是为什么页面的构造函数仅在第一次显示时才被执行的原因.因此,当您说要保留该图像时,我不确定您的意思.

Pages do not get destroyed when navigating to another page and coming back, which is why a page's constructor only gets executed the first time it is shown. So I am not sure what you mean when you say you want to hold that image.

话虽如此,您始终可以将整个profile变量分配给App类中的static全局变量,如下所示,以便无论如何都保持不变.然后,您必须在正确的时间分配/初始化全局变量.

Having said that, you could always assign the entire profile variable to a static global variable in your App class like below so that it stays the same no matter what. Then you would have to assign/initialize the global variable at the correct time.

但是同样,我不确定是否有必要,所以您可以尝试进一步解释问题的实质:

But again, I am not sure if that is necessary, so you might try to explain more what the issue actually is:

App类中:

public class App : Application {

    public static Image ProfileImage = new Image {
        Source            = "profile.png",
        HorizontalOptions = LayoutOptions.StartAndExpand,
        VerticalOptions   = LayoutOptions.StartAndExpand
    };
    ....
}

然后在您的页面中

public class ProfilePage : ContentPage {

    public ProfilePage() {

        ....

        App.ProfileImage.GestureRecognizers.Add(profiletap);
    }

}

此处中查看我的答案,该示例使用插件允许用户从自己的照片中选择照片设备的相机胶卷.一旦有了照片路径,就可以简单地使用HttpClient发送图像和base64字符串.在线上还有很多其他示例,关于如何做到这一点.

See my answer here for an example of using a plugin to allow the user to choose a photo from their device's camera roll. Once you have the photo path, you can simply use HttpClient to send the image and a base64 string. There are plenty of other example online about how to do that.

编辑#2:在这一行代码之后:

Edit #2: After this line of your code:

var file = await CrossMedia.Current.PickPhotoAsync();

您现在在file变量中具有文件和路径.因此,当前您要做的只是使用ImageSource.FromStream显示图像,但是为了在返回页面时继续显示图像,还需要将图像保存到设备中.为此,您将需要在每个项目中编写平台特定的代码,并在共享代码中引用该代码.像这样:

You now have the file and the path in file variable. So currently all you are doing is showing the image using ImageSource.FromStream but in order to keep showing the image when you return to the page, you need to also save the image to the device. In order to do that, you will need to write platform specific code in each project and reference that in your shared code. Something like this:

在您的iOS和Android项目中,创建一个新文件(例如,FileHelper_Android.csFileHelper_iOS.cs)并添加以下内容(可以将相同的代码添加到iOS和Android文件中,只需更改类的名称即可)和文件:

In your iOS and Android project, create a new file (FileHelper_Android.cs and FileHelper_iOS.cs for example) and add the following (the same code can be added to both iOS and Android files, just change the name of the class and file:

using ....;

[assembly: Dependency(typeof(FileHelper_Android))]

namespace YourNamespace.Droid{

    /// <summary>
    /// Responsible for working with files on an Android device.
    /// </summary>
    internal class FileHelper_Android : IFileHelper {

        #region Constructor

        public FileHelper_Android() { }

        #endregion

        public string CopyFile(string sourceFile, string destinationFilename, bool overwrite = true) {

            if(!File.Exists(sourceFile)) { return string.Empty; }
            string fullFileLocation = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.Personal), destinationFilename);
            File.Copy(sourceFile, fullFileLocation, overwrite);
            return fullFileLocation;
        }
    }
}

在iOS上执行相同的操作,只是更改文件名.现在,在您的共享项目中,您需要像这样创建IFileHelper.cs:

Do the same on iOS and just change the file name. Now in your shared project you need to create IFileHelper.cs like so:

public interface IFileHelper {

    string CopyFile(string sourceFile, string destinationFilename, bool overwrite = true);

}

最后,在您的页面中,您将编写以下内容:

Finally, in your page you would write the following:

_fileHelper = _fileHelper ?? DependencyService.Get<IFileHelper>();

profiletap.Tapped += async (s, e) =>
{
    var file = await CrossMedia.Current.PickPhotoAsync();
    if (file == null)
        return;
    await DisplayAlert("File Location", file.Path, "OK");

    profile.Source = im;

    imageName = "SomeUniqueFileName" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt");
    filePath  = _fileHelper.CopyFile(file.Path, imageName);

    im = ImageSource.FromFile(filePath)

//   await Navigation.PushModalAsync(new PhotoPage(im));
};

上面,一旦用户选择了文件,我们就会在本地复制该文件,并且还将您的im变量设置为新的本地文件路径,该路径将从IFileHelper.CopyFile方法返回.

Above, once the user chooses the file, we copy that file locally and the we also set your im variable to the new local file path, which gets returned from the IFileHelper.CopyFile method.

当用户返回页面或关闭并重新打开应用程序时,您仍然需要处理这种情况.在这种情况下,您需要加载保存的图像路径.我建议将图像路径保存到数据库中,除非用户只有一个配置文件图像,否则您总是可以加载相同的路径和文件名.让我知道您是否还有问题.

You still need to handle the case when the user comes back to the page or turns the app off and on again. In that situation, you need to load the saved image path. I would suggest either saving the image path into the DB, unless the user will only ever have a single profile image, then you could always just load that same path and filename. Let me know if you still have issues.

这篇关于Xamarin.forms导航另一页后如何在同一页上保留图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆