Maui Blazor 使用攝像頭實現(xiàn)代碼
由于Maui Blazor中界面是由WebView渲染,所以再使用Android的攝像頭時無法去獲取,因為原生的攝像頭需要綁定界面組件
所以我找到了其他的實現(xiàn)方式,通過WebView使用js調(diào)用設備攝像頭 支持多平臺兼容目前測試了Android 和PC 由于沒有ioc和mac無法測試 大概率是兼容可能需要動態(tài)申請權限
1. 添加js方法
我們再wwwroot中創(chuàng)建一個helper.js
的文件并且添加以下倆個js函數(shù)
再index.html
中添加<script src="helper.js"></script>
引入js
/** * 設置元素的src * @param {any} canvasId canvasId的dom id * @param {any} videoId video的dom id * @param {any} srcId img的dom id * @param {any} widht 設置截圖寬度 * @param {any} height 設置截圖高度 */ function setImgSrc(dest,videoId, srcId, widht, height) { let video = document.getElementById(videoId); let canvas = document.getElementById(canvasId); console.log(video.clientHeight, video.clientWidth); canvas.getContext('2d').drawImage(video, 0, 0, widht, height); canvas.toBlob(function (blob) { var src = document.getElementById(srcId); src.setAttribute("height", height) src.setAttribute("width", widht); src.setAttribute("src", URL.createObjectURL(blob)) }, "image/jpeg", 0.95); } /** * 初始化攝像頭 * @param {any} src */ function startVideo(src) { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) { let video = document.getElementById(src); if ("srcObject" in video) { video.srcObject = stream; } else { video.src = window.URL.createObjectURL(stream); } video.onloadedmetadata = function (e) { video.play(); }; //mirror image video.style.webkitTransform = "scaleX(-1)"; video.style.transform = "scaleX(-1)"; }); } }
然后各個平臺的兼容
android:
Platforms/Android/AndroidManifest.xml文件內(nèi)容
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:supportsRtl="true"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <!--相機權限--> <uses-permission android:name="android.permission.CAMERA" android:required="false"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!--相機功能--> <uses-feature android:name="android.hardware.camera" /> <!--音頻錄制權限--> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <!--位置權限--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> <uses-feature android:name="android.hardware.location.gps" /> <queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="http"/> </intent> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https"/> </intent> </queries> </manifest>
Platforms/Android/MainActivity.cs文件內(nèi)容
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] public class MainActivity : MauiAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Platform.Init(this, savedInstanceState); // 申請所需權限 也可以再使用的時候去申請 ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.Camera, Manifest.Permission.RecordAudio, Manifest.Permission.ModifyAudioSettings }, 0); } }
MauiWebChromeClient.cs文件內(nèi)容
#if ANDROID using Android.Webkit; using Microsoft.AspNetCore.Components.WebView.Maui; namespace MainSample; public class MauiWebChromeClient : WebChromeClient { public override void OnPermissionRequest(PermissionRequest request) { request.Grant(request.GetResources()); } } public class MauiBlazorWebViewHandler : BlazorWebViewHandler { protected override void ConnectHandler(Android.Webkit.WebView platformView) { platformView.SetWebChromeClient(new MauiWebChromeClient()); base.ConnectHandler(platformView); } } #endif
在MauiProgram.cs
中添加以下代碼;如果沒有下面代碼會出現(xiàn)沒有攝像頭權限
具體在這個 issue體現(xiàn)
#if ANDROID builder.ConfigureMauiHandlers(handlers => { handlers.AddHandler<IBlazorWebView, MauiBlazorWebViewHandler>(); }); #endif
以上是android的適配代碼 pc不需要設置額外代碼 ios和mac不清楚
然后編寫界面
@page "/" @*界面路由*@ @inject IJSRuntime JSRuntime @*注入jsRuntime*@ @if(OpenCameraStatus) @*在攝像頭沒有被打開的情況不顯示video*@ { <video id="@VideoId" width="@widht" height="@height" /> <canvas class="d-none" id="@CanvasId" width="@widht" height="@height" /> } <button @onclick="" style="margin:8px">打開攝像頭</button> @*因為攝像頭必須是用戶手動觸發(fā)如果界面是滑動進入無法直接調(diào)用方法打開攝像頭所以添加按鈕觸發(fā)*@ <button style="margin:8px">截圖</button> @*對視頻流截取一張圖*@ <img id="@ImgId" /> @code{ private string CanvasId; private string ImgId; private string VideoId; private bool OpenCameraStatus; private int widht = 320; private int height = 500; private async Task OpenCamera() { if (!OpenCameraStatus) { // 由于打開攝像頭的條件必須是用戶手動觸發(fā)如果滑動切換到界面是無法觸發(fā)的 await JSRuntime.InvokeVoidAsync("startVideo", "videoFeed"); OpenCameraStatus = true; StateHasChanged(); } } protected override async Task OnInitializedAsync() { // 初始化id ImgId = Guid.NewGuid().ToString("N"); CanvasId = Guid.NewGuid().ToString("N"); VideoId = Guid.NewGuid().ToString("N"); await base.OnInitializedAsync(); } private async Task Screenshot() { await JSRuntime.InvokeAsync<String>("setImgSrc", CanvasId,VideoId, ImgId, widht, height); } }
然后可以運行程序就可以看到我們的效果了
到此這篇關于Maui Blazor 使用攝像頭實現(xiàn)的文章就介紹到這了,更多相關Maui Blazor 攝像頭內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Typora?0.11.18免費版本安裝使用教程(親測可用)
Typora是一款非常使用的筆記工具,對于程序員非常友好,在2021年11月23日,Typora?正式發(fā)布?1.0?版本,進入了付費時代,Typora免費版本0.11.18(最后的免費版),本文給大家分享Typora免費獲取方法及安裝使用教程,感興趣的朋友參考下吧2022-07-07gradle+shell實現(xiàn)自動系統(tǒng)簽名
這篇文章主要介紹了gradle+shell實現(xiàn)自動系統(tǒng)簽名的相關資料,需要的朋友可以參考下2019-08-08Elasticsearch索引的分片分配Recovery使用講解
這篇文章主要為大家介紹了Elasticsearch索引的分片分配Recovery使用講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04