2016-09-07 55 views
1

转换StackLayout如图片我的工作Xmarin形式(PCL)的项目,我想给StackLayout转换为图像/缓冲器并将其发送到打印机进行打印硬。在Xamarin

有人能想出如何做到这一点的(Xamarin.Android & Xamarin.iOS)。

回答

1

你不能。 Xamarin没有这种功能。你应该写你的UIComponent一个渲染器。

幸运的是,还有一个Objective-C iOS实现,以及Android。你可以从他们身上得到启发。

0

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; 
     } 
    } 
}