我的项目类型是xamarin形式的PCL。我想截屏,正在使用以下代码。但是,当我调试代码时,Activity
始终为null。我试图找出问题,但没有成功。你能告诉我我在做什么错吗。
public interface IScreenshotManager
{
Task<byte[]> CaptureAsync();
}
对于Android:
[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService))]
namespace MyProject.Droid
{
public class ScreenshotService : IScreenshotService
{
public static Activity Activity { get; set; }
public async System.Threading.Tasks.Task<byte[]> Capture()
{
if (Activity == null) // Activity is always null Error here
{
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;
}
}
}
调用函数
byte[] screenshotData = await DependencyService.Get<IScreenshotService>().Capture();
答案 0 :(得分:1)
如果您未分配,显然Activity
是null
。您可以使用CurrentActivity
nuget包来获取当前活动(或者您可以在Activity
OnCreate
方法中分配它,因为Xamarin从一开始就始终使用相同的Activity
)。
答案 1 :(得分:1)
The old deprecated way would be var view = ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView;
Xamarin automatically assigns the Activity
to Forms.Context
.Since the release of Xamarin 2.5, Xamarin.Forms.Forms.Context
is obsolete.
Now you could use this :
var currentContext = Android.App.Application.Context;