RenderTargetBitmap在Windows 8.1上运行正常,但在Windows Phone 8.1上运行不正常

时间:2015-02-13 14:11:42

标签: c# windows-runtime windows-phone windows-phone-8.1 windows-8.1

我正在制作通用应用。在我的应用程序中,我需要使用RenderTargetBitmap将图像和TextBlock转换为JPEG照片。 在Windows 8.1项目中,一切都按预期工作,但不在Windows Phone 8.1上。你能帮帮我吗? 谢谢。

我的代码如下:

async Task SaveVisualElementToFile(FrameworkElement element, StorageFile file, int imageWidth, int imageHeight)
    {
        var renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(element, imageWidth, imageHeight);
        var pixels = await renderTargetBitmap.GetPixelsAsync();

        using(IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            var encoder = await
                BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
            byte[] bytes = pixels.ToArray();
            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Ignore,
                                 (uint)imageWidth, (uint)imageHeight,
                                 96, 96, bytes);

            await encoder.FlushAsync();
        }
    }

它正在抛出错误     byte [] bytes = pixels.ToArray(); 错误是:     “指定的缓冲区索引不在缓冲区容量内”

我用这个方法调用方法:

    var file = await KnownFolders.CameraRoll.CreateFileAsync("abc.jpg", CreationCollisionOption.ReplaceExisting);
    Image image = new Image();
    image.Source = bitmapImage;
    image.VerticalAlignment = VerticalAlignment.Top;

    TextBlock tb = new TextBlock();
    tb.FontSize = bitmapImage.PixelHeight / 15;
    tb.Foreground = new SolidColorBrush(Colors.Yellow);
    tb.Text = "abcdefg";
    tb.VerticalAlignment = VerticalAlignment.Bottom;
    tb.HorizontalAlignment = HorizontalAlignment.Center;

    Grid grid = new Grid();
    grid.Children.Add(image);
    grid.Children.Add(tb);

    renderBmpGrid.Children.Add(grid); //renderBmpGrid is a Grid of
                                      //the visual tree
    await SaveVisualElementToFile(grid, file, bitmapImage.PixelWidth, bitmapImage.PixelHeight);

0 个答案:

没有答案