首页 文章

如何在用户打开xamarin表单应用程序时加载本机相机

提问于
浏览
1

你好我正在开发一个应用程序,允许用户拍摄笔记,然后发送给朋友 . 我正在使用xamarin表单构建这个应用程序,我也使用媒体插件访问本机相机,但用户必须按一个按钮打开本机相机所以我的问题是我如何让相机尽快加载用户打开应用程序?

继承我的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" x:Class="SnapNote.CameraPage"
xmlns:local="clr-namespace:AppName;"
    BackgroundColor="{x:Static local:Colors.BackgroundColor}">
    <ContentPage.Padding>
        <OnPlatform
            x:TypeArguments="Thickness"
            iOS="10,20,10,10"
            Android="10,10,10,10" />
    </ContentPage.Padding>
    <StackLayout>

        <Image Source="TakePhotoButton.png">
    <Image.GestureRecognizers>
        <TapGestureRecognizer
                Tapped="Handle_Clicked"  />
  </Image.GestureRecognizers>
</Image>

        <Image x:Name="image"/>


        <Image Source="SendNoteButton.png">

</Image>


    </StackLayout>
</ContentPage>

并且背后的代码:

using System;
using System.Collections.Generic;
using Plugin.Media;
using Plugin.Media.Abstractions;
using Xamarin.Forms;

namespace AppName
{
    public partial class CameraPage : ContentPage
    {
        public CameraPage()
        {
            InitializeComponent();
        }

        async void Handle_Clicked(object sender, System.EventArgs e)
        {
            await CrossMedia.Current.Initialize();

            var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                Directory = "MyPhoto",
                Name = "Nextflow.jpg",
                SaveToAlbum = true
            });

            if (file == null)
                return;

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

任何帮助都会很棒!

提前致谢!

1 回答

  • 1

    只需将相机逻辑移动到页面的OnAppearing事件中即可

    public override void OnAppearing() {
            await CrossMedia.Current.Initialize();
    
            var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                Directory = "MyPhoto",
                Name = "Nextflow.jpg",
                SaveToAlbum = true
            });
    
            if (file == null)
                return;
    
            image.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });
          }
    

相关问题