Windows 8.1 新控件和功能:

时间:2014-06-26 11:14:06   收藏:0   阅读:328

将 XAML 树呈现为位图:

适用于 Windows 8.1 的 Windows 运行时为 Windows.UI.Xaml.Media.Imaging 命名空间添加了一种新类型:RenderTargetBitmap

此类型提供了两个关键方法:

下例显示如何呈现 XAML 元素树。

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(myElementTree);

myImage.Source = renderTargetBitmap;

 

RenderTargetBitmap 继承自 ImageSource,因此可以直接将其设置为 Image 对象的源,而无需调用 GetPixelsAsync 以获取及显示位图数据。

下例显示如何将呈现的位图写入文件。

            var bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(this.C1);
            IBuffer buffer = await bitmap.GetPixelsAsync();
            var pixelStream = buffer.AsStream();


            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
            savePicker.FileTypeChoices.Add("Bitmap", new List<string>() { ".png" });
            savePicker.SuggestedFileName = "New Bitmap";

            StorageFile savedItem = await savePicker.PickSaveFileAsync();


            Guid encoderId = BitmapEncoder.PngEncoderId;
            IRandomAccessStream fileStream = await savedItem.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, fileStream);
            byte[] pixels = new byte[pixelStream.Length];
            pixelStream.Read(pixels, 0, pixels.Length);

            //pixal format shouldconvert to rgba8
            for (int i = 0; i < pixels.Length; i += 4)
            {
                byte temp = pixels[i];
                pixels[i] = pixels[i + 2];
                pixels[i + 2] = temp;
            }

            encoder.SetPixelData(
             BitmapPixelFormat.Rgba8,
             BitmapAlphaMode.Straight,
             (uint)bitmap.PixelWidth,
             (uint)bitmap.PixelHeight,
             96, // Horizontal DPI
             96, // Vertical DPI
             pixels);

            await encoder.FlushAsync();

 

MetroApp保存UIEment为图片 http://www.cnblogs.com/manupstairs/p/3556642.html 的代码 也差不多。其//pixal format shouldconvert to rgba8 下面的一段交换代码不用会变色。

 

Windows 8.1 新控件和功能:,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!