2013-08-05 30 views

Trả lời

14

Thậm chí tao nhã hơn:

UIScreen.MainScreen.Capture(); 
+0

Awesome! Tôi không biết điều đó;) – rFlex

+0

những gì nó trả về byte []? hoặc hình ảnh? –

+0

UIImage: https://developer.xamarin.com/api/member/UIKit.UIScreen.Capture()/ –

3

từ Craig Dunn's trang web:

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"); 
    } 
} 
2

Nhiều thanh lịch:

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

} 

Gọi UIViewExtensions.TakeScreenshot() để chụp ảnh màn hình toàn bộ màn hình hoặc bạn có thể gọi AsImage() cho bất kỳ chế độ xem nào để có được biểu diễn UIImage của chế độ xem. Sẽ tốt hơn nếu đặt phương thức TakeScreenshot() ở một nơi khác vì nó không phải là phần mở rộng của lớp UIView.