简体   繁体   English

如何初始化用相机拍照

[英]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.我试图让 profileImage 单击以允许用户设置个人资料图像,但是每当我单击应用程序中的图像时,什么都没有显示。有时应用程序无法响应。 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.我还意识到,一些问题反映在我在 Visual Studio 中的代码中,如附图所示。 enter image description here在此处输入图像描述

First,check your Activity,Whetherit has the attribute Theme .首先,检查您的 Activity,是否具有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/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其次,如果你的活动扩展了AppCompatActivity ,你应该使用主题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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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