圖片拼接是拼圖中一種,即將若干圖片拼接成一張大圖。本文將講述如何在windows phone中實現圖片的拼接。
首先,我們准備一些拼圖的原始圖片,這些圖片的長度、寬度各不一樣,並且也不是等比例。
private int width = 480; private int totalHeight = 0; string[] array = new string[] { "1.jpg", "2.jpg", "3.jpg", "4.jpg" }; WriteableBitmap[] imagearray; int[] heightarray;
一些常量的定義,array數組存儲的是待拼接的圖片列表
imagearray存儲的是圖片對應的WriteableBitamp對象
heightarray存儲的是圖片按比例縮放后的高度(寬度都為480)
totalHeight表示圖片拼接后的總高度
我們在頁面中方式一個ScrollViewer,然后將圖片都放置在一個Canvas中,設置圖片的距離頂部距離,最后將Canvas方式到ScrollViewer中:
private void Join() { //images container Canvas canvas = new Canvas(); //init array imagearray = new WriteableBitmap[array.Length]; heightarray = new int[array.Length]; for (int i = 0; i < array.Length; i++) { WriteableBitmap bitmap = FromContent(string.Format("Images/{0}", array[i])); double wr = width / (double)bitmap.PixelWidth; int height = (int)(bitmap.PixelHeight * wr); Image img = new Image() { Source = bitmap, Stretch = Stretch.Fill, Width = width, Height = height }; Canvas.SetLeft(img, 0); Canvas.SetTop(img, totalHeight); canvas.Children.Add(img); totalHeight += height; imagearray[i] = bitmap; heightarray[i] = height; } canvas.Height = totalHeight; scrollviewer.Content = canvas; }
其中需要注意的就是將圖片按比例縮放,為了防止保存圖片時候重新計算一遍高度,我們將高度和圖片保存到數據中。
下面來看一下保存的方法,我們需要得到一個ScrollViewer的WriteableBitmap,那么能不能使用直接對UI元素的截屏呢?答案是否定的,因為截屏我們只能得到屏幕大小的圖片,不能得到整個長圖。
那么我們應該怎么做呢,其實思路跟上面的展示方式一樣,我們將圖片拼接起來,具體的代碼如下:
//遍歷,將每張圖copy至大圖的相應位置 WriteableBitmap output = new WriteableBitmap(width, totalHeight); int toTop = 0; for (int i = 0; i < imagearray.Length; i++) { var wb = imagearray[i].Resize(width, heightarray[i], WriteableBitmapExtensions.Interpolation.NearestNeighbor); Rect dest = new Rect(0, toTop, width, heightarray[i]); Rect source = new Rect(0, 0, width, heightarray[i]); output.Blit(dest, wb, source); toTop += heightarray[i]; } SaveImage(output);
遍歷圖片,將圖片copy至一張大圖的某些部分
保存方法是將圖片保存到相冊中,當然我們也可以保存到獨立存儲空間中:
private void SaveImage(WriteableBitmap bit) { string msg = ""; try { byte[] imageBuffer; using (MemoryStream memoryStream = new MemoryStream()) { bit.SaveJpeg(memoryStream, bit.PixelWidth, bit.PixelHeight, 0, 100); imageBuffer = memoryStream.ToArray(); } using (MediaLibrary library = new MediaLibrary()) { library.SavePicture(string.Format("{0}.jpg", DateTime.Now.ToFileTime().ToString()), imageBuffer); } msg = "保存成功"; } catch (Exception ex) { msg = "保存失敗"; } finally { MessageBox.Show(msg); } }
源代碼你可以在這里找到.