轉換StackLayout如圖片我的工作Xmarin形式(PCL)的項目,我想給StackLayout轉換爲圖像/緩衝器並將其發送到打印機進行打印硬。在Xamarin
有人能想出如何做到這一點的(Xamarin.Android & Xamarin.iOS)。
轉換StackLayout如圖片我的工作Xmarin形式(PCL)的項目,我想給StackLayout轉換爲圖像/緩衝器並將其發送到打印機進行打印硬。在Xamarin
有人能想出如何做到這一點的(Xamarin.Android & Xamarin.iOS)。
你不能。 Xamarin沒有這種功能。你應該寫你的UIComponent一個渲染器。
幸運的是,還有一個Objective-C iOS實現,以及Android。你可以從他們身上得到啓發。
從this鏈接,我曾親自使用兩者,好半天回不過,下面的代碼將整個頁面的截圖。
我最終修改了代碼,僅截取了頁面上的特定視圖的屏幕截圖,並且還更改了其他一些內容,但此示例是我基於此的示例,請讓我知道您是否願意看到代碼和/或如果下面的東西不適合你。
首先,你在你的表格項目創建一個接口,IScreenshotManager.cs例如:
public interface IScreenshotManager {
Task<byte[]> CaptureAsync();
}
現在我們需要實現對Android的界面,ScreenshotManager_Android.cs例如:
public class ScreenshotManager : IScreenshotManager {
public static Activity Activity { get; set; }
public async System.Threading.Tasks.Task<byte[]> CaptureAsync() {
if(Activity == null) {
throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
}
var view = Activity.Window.DecorView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream()) {
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
}
然後在MainActivity
中設置ScreenshotManager.Activity
:
public class MainActivity : Xamarin.Forms.Platform.Android.FormsApplicationActivity {
protected override async void OnCreate(Android.OS.Bundle bundle) {
...
ScreenshotManager.Activity = this; //There are better ways to do this but this is what the example from the link suggests
...
}
}
最後,我們在iOS上實現這一點,讓去瘋狂並將它命名爲ScreenshotManager_iOS.cs:
public class ScreenshotManager : IScreenshotManager {
public async System.Threading.Tasks.Task<byte[]> CaptureAsync() {
var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
UIGraphics.BeginImageContext(view.Frame.Size);
view.DrawViewHierarchy(view.Frame, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
using(var imageData = image.AsPNG()) {
var bytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
return bytes;
}
}
}