Xamarin.Android 调用手机拍照功能
最近开发Android遇到了调用本地拍照功能,于是在网上搜了一些方法,加上自己理解的注释,在这儿记录下来省的下次用时候找不到,同事也给正在寻找调用本地拍照功能的小伙伴一些帮助~
实现思路:首先加载-->判断是否具备拍照功能-->创建图片目录(文件夹)-->点击拍照事件-->返回图片并绑定在控件上显示。
引用命名空间:
using System; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Content.PM; using Android.Graphics; using Android.OS; using Android.Provider; using Android.Widget; using Java.IO; using Environment = Android.OS.Environment; using Uri = Android.Net.Uri;
加载:
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); if (IsThereAnAppToTakePictures()) //判断本设备是否存在拍照功能 { CreateDirectoryForPictures(); Button button = FindViewById<Button>(Resource.Id.myButton); _imageView = FindViewById<ImageView>(Resource.Id.imageView1); button.Click += TakeAPicture; } }
判断是否具备拍照功能:
/// <summary> /// 判断是否具备拍照功能 /// </summary> /// <returns></returns> private bool IsThereAnAppToTakePictures() { Intent intent = new Intent(MediaStore.ActionImageCapture); IList<ResolveInfo> availableActivities = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly); return availableActivities != null && availableActivities.Count > 0; }
创建图片目录(文件夹):
/// <summary> /// 创建目录图片 /// </summary> private void CreateDirectoryForPictures() { App._dir = new File( Environment.GetExternalStoragePublicDirectory( Environment.DirectoryPictures), "CameraAppDemo"); //CameraAppDemo if (!App._dir.Exists()) { App._dir.Mkdirs(); } }
点击拍照事件:
/// <summary> /// 拍照 /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void TakeAPicture(object sender, EventArgs eventArgs) { Intent intent = new Intent(MediaStore.ActionImageCapture); App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid())); //保存路径 intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); StartActivityForResult(intent, 0); }
返回图片并绑定在控件上显示:
/// <summary> /// 拍照结束执行 /// </summary> /// <param name="requestCode"></param> /// <param name="resultCode"></param> /// <param name="data"></param> protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Uri contentUri = Uri.FromFile(App._file); mediaScanIntent.SetData(contentUri); SendBroadcast(mediaScanIntent); // Display in ImageView. We will resize the bitmap to fit the display // Loading the full sized image will consume to much memory // and cause the application to crash. int height = Resources.DisplayMetrics.HeightPixels; int width = _imageView.Height; //获取拍照的位图 App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height); if (App.bitmap != null) { //将图片绑定到控件上 _imageView.SetImageBitmap(App.bitmap); //清空bitmap 否则会出现oom问题 App.bitmap = null; } // Dispose of the Java side bitmap. GC.Collect(); }
LoadAndResizeBitmap方法:
public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height) { // First we get the the dimensions of the file on disk BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(fileName, options); // Next we calculate the ratio that we need to resize the image by // in order to fit the requested dimensions. int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > height || outWidth > width) { inSampleSize = outWidth > outHeight ? outHeight / height : outWidth / width; } // Now we will load the image and have BitmapFactory resize it for us. options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options); return resizedBitmap; }
App类:
public static class App { public static File _file; public static File _dir; public static Bitmap bitmap; }
最后再附上下载地址:
链接: https://pan.baidu.com/s/1h0Zg1jkCyKrZKN6N5eIB8Q
密码: wgdm

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
Android方法数methods超过65536
当Android App中的方法数超过65535时,如果往下兼容到低版本设备时,就会报编译错误: Cannot fit requested classes in a single dex file. Try supplying a main-dex list. # methods: 86204 > 65536 Message{kind=ERROR, text=Cannot fit requested classes in a single dex file. Try supplying a main-dex list. # methods: 86204 > 65536, sources=[Unknown source file], tool name=Optional.of(D8)} 原因是Android系统定义总方法数是一个short int,short int 最大值为65536。解决这个问题的方案是: 在Android的模块gradle文件的defaultConfig默认配置里面增加: multiDexEnabled true 同时在dependencies里面增加:...
- 下一篇
Xamarin.Android 调用本地相册
调用本地相册选中照片在ImageView上显示 代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Provider; using Android.Database; using System.Threading; using Java.IO; namespace CallLocalPhoto { [Activity(Label = "CallLocalPhoto", MainLauncher = true)] public class MainActivity : Activity { Button btn; ImageView iv; private Java.IO.File or...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS8编译安装MySQL8.0.19
- Windows10,CentOS7,CentOS8安装Nodejs环境
- CentOS关闭SELinux安全模块
- Windows10,CentOS7,CentOS8安装MongoDB4.0.16
- Linux系统CentOS6、CentOS7手动修改IP地址
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Red5直播服务器,属于Java语言的直播服务器
- SpringBoot2整合Redis,开启缓存,提高访问速度
- CentOS7,8上快速安装Gitea,搭建Git服务器