簡體   English   中英

如何使用Camera Xamarin Forms Android捕獲多張照片

[英]How to Capture multiple photos with Camera xamarin Forms android

我正在開發Xamrin表單應用程序。 在其中,我試圖使用具有相同意圖的相機捕獲多張照片。 不使用任何nuget包?

為此,我正在關注此鏈接相機

MainActivity.cs

static readonly File file = new File(Environment.GetExternalStoragePublicDirectory(
                                Environment.DirectoryPictures), "tmp.jpg");

在OnCreate的結尾

(Xamarin.Forms.Application.Current as App).ShouldTakePicture += () => {
    var intent = new Intent(MediaStore.ActionImageCapture);
    intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(file));
    StartActivityForResult(intent, 0);
};

在這里,單擊“相機”按鈕時我只會得到1張照片,但我想捕獲更多照片,並且想要其文件路徑

在OnActivityResult中

(Xamarin.Forms.Application.Current as App).ShowImage(file.Path);

但也許沒有什么限制,例如我們一次不能拍攝多張照片? 有誰知道如何捕獲多張照片並將其綁定到Listview?

是的,經過這么多的努力,我能夠做到這一點。 這可能會對從事xamarin形式的此類工作的人有所幫助。

這是我的代碼

 public partial class App : Application
    {
       // public static App Instance;

        public App ()
        {
            MainPage = new CameraGallery.MainPage();
            InitializeComponent();
        }
    }

MainPage.xaml

//請安裝FlowListView和ffimageloading nuget pckg

<?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:CameraGallery"
             x:Class="CameraGallery.MainPage"
             xmlns:flv="clr-namespace:DLToolkit.Forms.Controls;assembly=DLToolkit.Forms.Controls.FlowListView"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"> 

            <StackLayout x:Name="CameraLayout">
                <flv:FlowListView FlowColumnCount="3" x:Name="listItemsCam" 
                        SeparatorVisibility="None"
                        HasUnevenRows="false" RowHeight="100" >
                    <flv:FlowListView.FlowColumnTemplate>
                        <DataTemplate >
                            <ffimageloading:CachedImage  DownsampleToViewSize="true" AbsoluteLayout.LayoutFlags="All" HeightRequest="100" AbsoluteLayout.LayoutBounds="0,0,1,1" Source="{Binding .}"  Aspect="AspectFill" HorizontalOptions="FillAndExpand">
                            </ffimageloading:CachedImage>
                        </DataTemplate>
                    </flv:FlowListView.FlowColumnTemplate>
                </flv:FlowListView>
                <!--<Image x:Name="image" IsVisible="False"></Image>-->
            </StackLayout>
</ContentPage>  

MainPage.xaml.cs

 public partial class MainPage : ContentPage
        {
            ObservableCollection<string> camImageCollection;
            public static MainPage Instance;

            public MainPage()
            {
                InitializeComponent();
                Instance = this;

                var btn = new Button
                {
                    Text = "Snap!",
                    Command = new Command(o => ShouldTakePicture()),
                };
                CameraLayout.Children.Add(btn);  

                camImageCollection = new ObservableCollection<string>();
            }
            public event Action ShouldTakePicture = () => { };

            public void ShowImage(string[] filepath)
            {
               foreach(var item in filepath)
                 camImageCollection.Add(item);
                 listItemsCam.FlowItemsSource = camImageCollection;
            }
        }

現在轉到MainActivity.cs中的android項目

[Activity(Label = "CameraGallery", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public static int OPENCAMERACODE = 102;
        //inside OnCreate after LoadApplication(new App()); add these lines
         protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
            UserDialogs.Init(this);
            base.OnCreate(bundle);

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

            FlowListView.Init();
            CachedImageRenderer.Init(false);
            LoadApplication(new App());
            MainPage.Instance.ShouldTakePicture += () =>
            {
                ICursor cursor = loadCursor();
                image_count_before = cursor.Count;
                cursor.Close();
                Intent intent = new Intent(MediaStore.IntentActionStillImageCamera);
                IList<ResolveInfo> activities = PackageManager.QueryIntentActivities(intent, 0);
                if(activities.Count >0)
                    StartActivityForResult(Intent.CreateChooser(intent, "Camera Capture"), OPENCAMERACODE);
            };
        }
        public ICursor loadCursor()
        {
            string[] columns = new string[] { MediaStore.Images.ImageColumns.Data, MediaStore.Images.ImageColumns.Id };
            string orderBy = MediaStore.Images.ImageColumns.DateAdded;
            return ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, columns, null, null, orderBy);
        }
        private void exitingCamera()
        {
            ICursor cursor = loadCursor();
            string[] paths = getImagePaths(cursor, image_count_before);
            MainPage.Instance.ShowImage(paths);// this parameter pass to MainPage.xaml.cs
            cursor.Close();
        }
        public string[] getImagePaths(ICursor cursor, int startPosition)
        {
            int size = cursor.Count - startPosition;
            if (size <= 0) return null;
            string[] paths = new string[size];

            int dataColumnIndex = cursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
            for (int i = startPosition; i < cursor.Count; i++)
            {
                cursor.MoveToPosition(i);

                paths[i - startPosition] = cursor.GetString(dataColumnIndex);
            }
            return paths;
        }
        //inside OnActivityResult method do this
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            switch (requestCode)
            {
                case 102:
                        exitingCamera();
                    break;
            }
        }
    }   

我希望這可以幫助某人。 享受編碼...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM