背景: android 和windows phone 都沒有隨手截屏功能,這點比iphone差了些。當然這是閑話,和我們的程序無關。
windows phone 平台上調用新浪微博開發接口,發送微博的函數為:
SdkShare sdkShare = new SdkShare { AccessToken = App.AccessToken, PicturePath = "TempJPEG.jpg", Message = this.messageTextBlock.Text };
其中有一項 PicturePath 。 它是在windows phone 中的 IsolatedStorageFile 存儲空間里的。 所以要想發送一張含圖片的 微博,首先要在windows phone 的獨立存儲空間里面有源圖片。
下面進入正題。我想把當前屏幕畫面,或者屏幕的部分內容保存為一張圖片。可以用WriteableBitmap 來實現。
1 private void button1_Click(object sender, RoutedEventArgs e) 2 { 3 ScaleTransform transform = new ScaleTransform(); 4 transform.ScaleX = 1; 5 transform.ScaleY = 1; 6 7 System.Windows.Media.Imaging.WriteableBitmap we = new System.Windows.Media.Imaging.WriteableBitmap(this, transform); 8 img.Source = we; // img 是一個image控件 9 Save(we); 10 } 11 12 private void Save(System.Windows.Media.Imaging.WriteableBitmap we) 13 { 14 MemoryStream stream = new MemoryStream(); 15 we.SaveJpeg(stream,we.PixelWidth,we.PixelHeight,0,100); 16 stream.Seek(0,SeekOrigin.Begin); 17 IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
18 19 Stream istream = new IsolatedStorageFileStream("screen.jpg", FileMode.Create, fileStorage); 20 stream.CopyTo(istream); 21 stream.Close(); 22 istream.Close(); 23 25 }
WriteableBitmap(this, transform),this 是指把整個頁面都截下來。當然可以截取部分,那么就把this改成this.gridName 等等。
img.Source = we;是直接用截屏的內容作為xaml的image控件的內容。 如果我想讓image的內容指向isolatedStorage存儲空間內的圖片,則需要這樣:
1 BitmapImage bmp = new BitmapImage(); 2 using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) 3 using (var stream = isolatedStorageFile.OpenFile("screen.jpg", FileMode.Open, FileAccess.Read)) 4 { 5 bmp.SetSource(stream); 6 } 7 img.Source = bmp;
用一個BitmapImage 承載圖片的內容。
這里是源碼 下載后去掉.jpg