使用Xamarin.Forms中的Acr.XamForms Nuget访问Camera和Gallery的示例代码

时间:2014-09-22 12:33:22

标签: android ios xamarin xamarin.forms

有没有人可以在Xamarin.Forms 中使用Acr.XamForms Nuget为相机和图库访问提供链接/示例代码?

我来自here的代码,但我想在我的PCL中使用Acr.XamForms nuget包执行功能 [并不包含在特定于设备的项目中]

提前致谢!

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

我花时间研究ACR样本,但仍然没有完全弄清楚它们是如何组合在一起的。所以我最终从头开始,编写App.cs文件中的所有内容,并通过试用/错误提出了这个非常简单的解决方案,适用于iOS和Android。它允许您从图库中获取图像或拍照,完成后会显示照片。希望这可以帮助别人节省几个小时。

我还要向所有努力为社区创建优秀图书馆的人致以请求:请提供超简单的使用示例。不要创建一个精心设计的示例来演示您的库...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Xamarin.Forms;
using Acr.XamForms.Mobile.Media;

namespace photoSimpleTest
{
    public class App : Application
    {
        MediaPicker mPick = new MediaPicker();

        Image ShowPic;

        public App ()
        {
            var showGalleryButton = new Button {
                Text="Show Gallery"
            };
            showGalleryButton.Clicked += ShowGallery;

            var takePictureButton = new Button
            {
                Text = "Take Picture"
            };
            takePictureButton.Clicked += TakePicture;

            ShowPic = new Image();

            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        showGalleryButton,
                        takePictureButton,
                        ShowPic
                    }
                }
            };
        }

        public async void ShowGallery(object s, EventArgs a) 
        {
            if (!mPick.IsPhotoGalleryAvailable)
                Debug.WriteLine("Photo Gallery is unavailable");
            else
            {
                var result = await mPick.PickPhoto();
                PhotoReceived(result);
            }
        }

        public async void TakePicture(object s, EventArgs a)
        {
            if (!mPick.IsCameraAvailable)
                Debug.WriteLine("Camera is not available");
            else
            {
                var opt = new CameraOptions { };
                var result = await mPick.TakePhoto(opt);
                PhotoReceived(result);
            }
        }

        private void PhotoReceived(IMediaFile file)
        {
            if (file == null)
                Debug.WriteLine("Photo Cancelled");
            else
                ShowPic.Source = ImageSource.FromFile(file.Path);
        }
    }
}