RenderTargetBitmap工作正常的Windows 8.1,但不是在Windows Pho

2019-10-21 20:42发布

我正在做一个通用的应用程序。 在我的应用我需要使用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();
        }
    }

它引发错误的行字节[]字节= 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);
文章来源: RenderTargetBitmap works fine on Windows 8.1, but not on Windows Phone 8.1