简体   繁体   中英

How to initialize Take photo with camera

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);
        }
    }
}

I have tried to get profileImage click to allow the user to set up the profile image, but at whenever i click the image in the the app, nothing is showing up.At some point the app fail to respond. what could be the problem. I have installed all the plugin needed and done all I think was expected.

I have also realized that some issues reflects in my code in visual studio as attached picture. enter image description here

First,check your Activity,Whetherit has the attribute Theme .

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

you could define a theme in your 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>

Second,if your activity extends AppCompatActivity ,you should use the theme theme.appcompat.xxx

Update :

try to change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM