Как инициализировать Сделать фото с помощью камеры - PullRequest
0 голосов
/ 12 июля 2020
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Plugin.Media;

using Refractored.Controls;
using Uber_Driver.Activities;

namespace Uber_Driver.Fragments
{
    public class AccountFragment : Android.Support.V4.App.Fragment
    {
        ImageView profileImage;
        Button logoutButton;

        readonly string[] permissionGroup =
        {
            Manifest.Permission.ReadExternalStorage,
            Manifest.Permission.WriteExternalStorage,
            Manifest.Permission.Camera
        };
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            

            // Create your fragment here


        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            View view = inflater.Inflate(Resource.Layout.account, container, false);

            profileImage = (ImageView)view.FindViewById(Resource.Id.profileImage);

            profileImage.Click += ProfileImage_Click;
            logoutButton = (Button)view.FindViewById(Resource.Id.LogoutButton);
            logoutButton.Click += LogoutButton_Click;

            
            return view;
        }

        private void ProfileImage_Click(object sender, EventArgs e)
        {
            Android.Support.V7.App.AlertDialog.Builder photoAlert = new Android.Support.V7.App.AlertDialog.Builder(Android.App.Application.Context);
            photoAlert.SetMessage("Change Photo");
            

            photoAlert.SetNegativeButton("Take Photo", (thisalert, args) =>
            {
                //capture
               TakePhoto();
            });

            photoAlert.SetPositiveButton("Upload Photo", (thisAlert, args) =>
            {
                // Choose Image
                SelectPhoto();
            });

            photoAlert.Show();


        }

        async void TakePhoto()
        {
            await CrossMedia.Current.Initialize();
            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                CompressionQuality = 20,
                Directory = "Sample",
                Name = GenerateRadomString (6) + "profileImage.jpg"
                
            });

            if (file == null)
            {
                return;
            }

            //Converts file.path to byte array and set the resulting bitmap to imageview
            byte[] imageArray = System.IO.File.ReadAllBytes(file.Path);
            

            
            Bitmap bitmap = BitmapFactory.DecodeByteArray(imageArray, 0, imageArray.Length);
            profileImage.SetImageBitmap(bitmap);

        }

        async void SelectPhoto()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                Toast.MakeText(Android.App.Application.Context, "Upload not supported", ToastLength.Short).Show();
                return;
            }

            var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                CompressionQuality = 30,
            });

            if (file == null)
            {
                return;
            }

            byte[] imageArray = System.IO.File.ReadAllBytes(file.Path);
            

            Bitmap bitmap = BitmapFactory.DecodeByteArray(imageArray, 0, imageArray.Length);
            profileImage.SetImageBitmap(bitmap);

        }



        string GenerateRadomString(int length)
        {
            Random rand = new Random();
            char[] allowchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray();
            string sResult = "";
            for (int i = 0; i <= length; i++)
            {
                sResult += allowchars[rand.Next(0, allowchars.Length)];
            }

            return sResult;
        }

        private void LogoutButton_Click(object sender, EventArgs e)
        {
            StartActivity(new Intent(Application.Context, typeof(LoginActivity)));
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

Я попытался получить щелчок profileImage, чтобы пользователь мог настроить изображение профиля, но всякий раз, когда я щелкаю изображение в приложении, ничего не отображается. В какой-то момент приложение не отвечает. В чем может быть проблема. Я установил весь необходимый плагин и сделал все, что я ожидал.

Я также понял, что некоторые проблемы отражаются в моем коде в Visual Studio в виде прикрепленного изображения. введите описание изображения здесь

1 Ответ

0 голосов
/ 13 июля 2020

Сначала проверьте свою активность, есть ли у нее атрибут Theme.

[Activity(Label = "@string/app_name", Theme = "@style/MyTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity

, вы можете определить тему в своем Resources/values/styles.xml:

<resources>
<!-- Base application theme. -->
<style name="MyTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    ...
</style>

Во-вторых, если ваш активность расширяется AppCompatActivity, вам следует использовать тему theme.appcompat.xxx

Обновление :

попробуйте изменить

Android.Support.V7.App.AlertDialog.Builder photoAlert = new Android.Support.V7.App.AlertDialog.Builder(Android.App.Application.Context);

на

Android.Support.V7.App.AlertDialog.Builder photoAlert = new Android.Support.V7.App.AlertDialog.Builder(Activity);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...