2016-06-10 86 views
0

以下代码读取图像,并将该图像居中(剪切并复制)到带有黑色框的结果图像中,以返回新图像。UWP - 如何在后台任务中使用WriteableBimap?另类?

我可以不使用writeablebitmap类吗?

private async Task<WriteableBitmap> FrameToCenter(StorageFile image, Size newSize) 
    { 
     WriteableBitmap result = new WriteableBitmap((int) newSize.Width,(int) newSize.Height); 

     WriteableBitmap bitmapToFrame = await StorageFileToSoftwareBitmap(image); 

     Rect sourceRect = new Rect(0, 0, bitmapToFrame.PixelWidth, bitmapToFrame.PixelHeight); 
     int a = (int) Math.Min(newSize.Height, newSize.Width); 
     Rect destRect = new Rect((int) ((_screenResolution.Width - _screenResolution.Height)/2), 0, a, a); 

     result.Blit(destRect, bitmapToFrame, sourceRect); 

     return result; 
    } 

一切工作正常,但后来我试图把该代码放到一个BackgroundTask在UWP,是由于这样的事实结果的异常,我不能在不同的线程,则UI线程中使用WriteableBitmap的。

还有什么我可以做的吗?我需要在背景任务中运行它。

除了行:

result.Blit(destRect, bitmapToFrame, sourceRect); 

实际使用WriteableBitmapEx扩展,我将无法使用。任何其他方式?我真的没有看到如何操作后台任务线程上的位图。我很安静地迷失在这里。我一直在考虑使用openCV库,只用C++来做,会解决问题吗?

还有this SO Q&A,其中提到我应该从XamlRenderingBackgroundTask class推导出我的背景任务。我怎样才能做到这一点?

回答

0

您使用XamlBackgroundTask以同样的方式,你会经常BackgroundTask

public sealed class MyBackgroundTask : XamlRenderingBackgroundTask 
{ 
    protected override async void OnRun(IBackgroundTaskInstance taskInstance) 
    { 
     var deferral = taskInstance.GetDeferral(); 
     //your code here 
     deferral.Complete(); 
    } 
} 

不同的是,这将有机会获得UI线程,所以你可以使用你的WriteableBitmap的。

我只是留意this文章中的重要建议。

重要为了尽可能降低后台任务的内存占用量,此任务应该在Windows Phone的C++ Windows运行时组件中实现。如果使用C#编写,内存占用将会更高,并且会导致内存不足,从而终止后台任务。有关内存限制的更多信息,请参阅使用后台任务支持您的应用程序。

+0

如果我的任务是密封类,我该如何继承?我没有明白。 – pijemcolu

+0

你不从*你的*任务继承。你的任务继承自XamlBackgroundRenderingTask – AlexDrenea