如何使用 Xamarin.iOS 截屏并将此图像存储在 UIImage 中。
我看过几个 Obj-C 的例子,但是没有 C#
如何使用 Xamarin.iOS 截屏并将此图像存储在 UIImage 中。
我看过几个 Obj-C 的例子,但是没有 C#
更优雅:
UIScreen.MainScreen.Capture ();
更优雅:
public static class UIViewExtensions {
public static UIImage AsImage(this UIView view) {
UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, view.Opaque, 0);
view.Layer.RenderInContext(UIGraphics.GetCurrentContext());
UIImage img = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return img;
}
public static UIImage TakeScreenshot() {
return UIApplication.SharedApplication.KeyWindow.AsImage();
}
}
调用 UIViewExtensions.TakeScreenshot() 来截取整个屏幕的屏幕截图,或者您可以调用 AsImage() 到任何视图以获取视图的 UIImage 表示。最好将 TakeScreenshot() 方法放在其他地方,因为它不是 UIView 类的扩展。
来自克雷格邓恩的网站:
public void ScreenCapture()
{
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
Console.WriteLine("start capture of frame: " + this.View.Frame.Size);
UIGraphics.BeginImageContext(View.Frame.Size);
var ctx = UIGraphics.GetCurrentContext();
if (ctx != null)
{
View.Layer.RenderInContext(ctx);
UIImage img = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
// Set to display in a UIImage control _on_ the view
imageLogo.Image = img;
// Save to Photos
img.SaveToPhotosAlbum(
(sender, args)=>{Console.WriteLine("image saved to Photos");}
);
// Save to application's Documents folder
string png = Path.Combine (documentsDirectory, "Screenshot.png");
// HACK: overwrite the splash screen. iSOFlair is the application name
//string png = Path.Combine (documentsDirectory, "../iSOFlair.app/Default.png");
NSData imgData = img.AsPNG();
NSError err = null;
if (imgData.Save(png, false, out err))
{
Console.WriteLine("saved as " + png);
} else {
Console.WriteLine("NOT saved as" + png +
" because" + err.LocalizedDescription);
}
}
else
{
Console.WriteLine("ctx null - doesn't seem to happen");
}
}
此代码将截取屏幕并将照片保存到相机胶卷中。
UIGraphics.BeginImageContext(UIScreen.MainScreen.Bounds.Size);
try
{
var mainLayer = UIApplication.SharedApplication.KeyWindow.Subviews[0].Layer;
mainLayer.RenderInContext(UIGraphics.GetCurrentContext());
var img = UIGraphics.GetImageFromCurrentImageContext();
img.SaveToPhotosAlbum((iRef, status) =>
{
if (status != null)
{
new UIAlertView("Problem", status.ToString(), null, "OK", null).Show();
}
else
{
new UIAlertView("Saved", "Saved", null, "OK", null).Show();
}
});
}
finally
{
UIGraphics.EndImageContext();
}
但是要确保您的应用程序没有崩溃,请询问用户是否允许将图像保存到相机胶卷。将此添加到 info.plist
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app requires read and write permission from the user.</string>
if you're adding it from the generic editor then "Privacy - Photo Library Additions Usage Description" will be the given option you will find out instead of "NSPhotoLibraryAddUsageDescription".