Maui 教學 – 好了, 今次我們就會說說Maui Camera及Maui Photo Video Picker的功能. Maui提供了四個主要的methods, 分別為:
- PickPhotoAsync
- CapturePhotoAsync
- PickVideoAsync
- CaptureVideoAsync.
四個的methods好處 – PickPhotoAsync, CapturePhotoAsync, PickVideoAsync, CaptureVideoAsync
Maui的好處為使用方便, 五到十句Code, 可以Output到Stream, 再轉為File或MemoryStream. 其次為Cross platform, 一套CODE可重覆使用在不同的系統上.
最基本的使用方法為融合App本身的功能拍攝日常生活, 工作情況. 如投訴App提供的相片証明等. 用法多的事, 不多說了.
現在介紹Camera及Photo Video Picker的Code. Let’s Code!
IOS |
Platforms/iOS/Info.plist Platforms/MacCatalyst/Info.plist – 在此檔案下加入以下CODE: |
<key>NSCameraUsageDescription</key> <string>This app needs access to the camera to take photos.</string> <key>NSMicrophoneUsageDescription</key> <string>This app needs access to microphone for taking videos.</string> <key>NSPhotoLibraryAddUsageDescription</key> <string>This app needs access to the photo gallery for picking photos and videos.</string> <key>NSPhotoLibraryUsageDescription</key> <string>This app needs access to photos gallery for picking photos and videos.</string> |
Android |
Platforms/Android/MainApplication.cs – 在此檔案下加入以下CODE: |
[assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)] [assembly: UsesPermission(Android.Manifest.Permission.Camera)] [assembly: UsesFeature(“android.hardware.camera”, Required = true)] [assembly: UsesFeature(“android.hardware.camera.autofocus”, Required = true)] |
Platforms/Android/AndroidManifest.xml – 在此檔案下加入以下CODE: |
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” /> <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /> <uses-permission android:name=”android.permission.CAMERA” /> |
Platforms/Android/AndroidManifest.xml 如果專案的Target為Android 11 (R API 30) 或更高, 需加入以下CODE. |
<queries> <intent> <action android:name=”android.media.action.IMAGE_CAPTURE” /> </intent> </queries> |
Code |
if (MediaPicker.Default.IsCaptureSupported) { FileResult video = await MediaPicker.Default.PickVideoAsync (); if (photo != null) { // 存儲檔案至LOCAL STORAGE string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName); using Stream sourceStream = await photo.OpenReadAsync(); using FileStream localFileStream = File.OpenWrite(localFilePath); await sourceStream.CopyToAsync(localFileStream); } } } |
PickVideoAsync可換為PickPhotoAsync, CapturePhotoAsync, PickVideoAsync 或CaptureVideoAsync |