如何将相机拍摄的图像添加到Listview? Xamarin形式

时间:2019-01-29 13:40:39

标签: forms xamarin

我想在相机拍摄完每张图像后,将图像添加到Xamarin Forms(或其他布局)的Listview中吗?我将如何处理? Something like this photo

我使用https://github.com/jamesmontemagno/MediaPlugin示例拍摄/挑选照片,但是不确定如何将它们添加到Xamarin表单的Listview或其他布局中

3 个答案:

答案 0 :(得分:2)

您需要对此进行修改,以使其正常工作并完全按照您的要求进行操作,但这确实有效。重构为MVVM,在需要的地方添加绑定,并确保更改对您不起作用的所有方面。

我已经在iOS上进行过测试,但未在Android上进行过测试。鉴于是Forms,您唯一需要做的就是已经完成的工作,然后初始化Media插件。

鉴于它非常动态,所有可视化工作都已在视图中完成(后面的代码)。

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="PlaypenApp.ImageGridPage">

    <ScrollView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <Grid x:Name="ImageGridContainer" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Padding="5">
            <Grid.RowDefinitions>
                <RowDefinition Height="1" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>            
        </Grid>        
    </ScrollView>    
</ContentPage>

C#(后面的代码)

using System;
using System.Threading.Tasks;

using Xamarin.Forms;

using Plugin.Media;
using Plugin.Media.Abstractions;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;

namespace PlaypenApp
{
    public partial class ImageGridPage : ContentPage
    {
        private const int MaxColumns = 3;

        private double _rowHeight = 0;
        private int _currentRow = 0;
        private int _currentColumn = 0;

        public ImageGridPage()
        {
            InitializeComponent();

            Device.BeginInvokeOnMainThread(async () => await InitialiseMediaPermissions());

            var addPhotoButton = new Button()
            {
                Text = "Add Photo",
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                BorderColor = Color.FromHex("#F0F0F0"),
                BorderWidth = 1,
                BackgroundColor = Color.FromHex("#F9F9F9"),
                TextColor = Color.Black,
                FontAttributes = FontAttributes.Bold
            };

            addPhotoButton.Clicked += async (object sender, EventArgs e) => await AddPhoto();

            ImageGridContainer.Children.Add(addPhotoButton, 0, 0);

            Device.BeginInvokeOnMainThread(async () =>
            {
                // Wait for a small amount of time so the UI has a chance to update the relevant values
                // we need to complete the operation.
                await Task.Delay(10);

                // Set the row height to be the same as the column width so that the image 
                // is presented in a square grid.
                _rowHeight = addPhotoButton.Width;
                ImageGridContainer.RowDefinitions[0].Height = _rowHeight;

                await ImageGridContainer.FadeTo(1);
            });
        }

        async Task AddPhoto()
        {
            MediaFile file = null;

            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("No Camera", "You need to fix the problem of camera availability", "OK");
                return;
            }

            var imageSource = await DisplayActionSheet("Image Source", "Cancel", null, new string[] { "Camera", "Photo Gallery" });
            var photoName = Guid.NewGuid().ToString() + ".jpg";

            switch (imageSource)
            {
                case "Camera":
                    file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                    {
                        Directory = "Sample",
                        Name = photoName
                    });

                    break;

                case "Photo Gallery":
                    file = await CrossMedia.Current.PickPhotoAsync();

                    break;

                default:
                    break;
            }

            if (file == null)
                return;

            // We have the photo, now add it to the grid.
            _currentColumn++;

            if (_currentColumn > MaxColumns - 1)
            {
                _currentColumn = 0;
                _currentRow++;

                // Add a new row definition by copying the first row.
                ImageGridContainer.RowDefinitions.Add(ImageGridContainer.RowDefinitions[0]);
            }

            var newImage = new Image()
            {
                Source = ImageSource.FromFile(file.Path),
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Aspect = Aspect.AspectFill,
                Scale = 0
            };

            ImageGridContainer.Children.Add(newImage, _currentColumn, _currentRow);

            await Task.Delay(250);

            await newImage.ScaleTo(1, 250, Easing.SpringOut);
        }

        async Task InitialiseMediaPermissions()
        {
            var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
            var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);

            if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted)
            {
                var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera, Permission.Storage });
                cameraStatus = results[Permission.Camera];
                storageStatus = results[Permission.Storage];
            }
        }
    }
}

...实际上,我实际上只是根据需要向网格中动态添加行。

我希望无论如何能帮助您。

让我知道你的生活。

答案 1 :(得分:1)

自Xamarin Forms 3.0以来,可以使用Flexlayout来实现

答案 2 :(得分:0)

enter image description here

这只是Brad代码的简要快照。

//if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            //{
            //    await DisplayAlert("No Camera", "You need to fix the problem of camera availability", "OK");
            //    return;
            //}

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                return;
            }

如果有人在模拟器上运行它,则将验证检查更改为IsPickPhotoSupported,因为Camera控件无法在模拟器上运行(或者仅仅是我吗?)。