2

Windows Phone 8.1 (C#) アプリケーションの JPG/PNG/BMP イメージでプログラムによって作成された UIElement を保存しようとしています。

メソッド RenderAsync() を使用してクラス RenderTargetBitmap を使用していますが、XAML コードで作成された UI 要素でのみ機能します。C# で直接作成された UI 要素で使用すると、「System.ArgumentException (値が期待される範囲内にありません。)」という例外が発生します。

私は何か間違ったことをしていますか、それともこのクラスはプログラムで作成された UIElement(s) のレンダリングを許可していませんか? Windows Phone 8.1 でこれを行う方法はありますか? ありがとうございました!

私が使用するコードは次のとおりです。

        private static async void RenderText(string text, int width, int height, int fontsize, string imagename)
    {
        RenderTargetBitmap b = new RenderTargetBitmap();

        var canvas = new Grid();

        canvas.Width = width;
        canvas.Height = height;

        var background = new Canvas();
        background.Height = width;
        background.Width = height;

        SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
        background.Background = backColor;

        var textBlock = new TextBlock();
        textBlock.Text = text;
        textBlock.FontWeight = FontWeights.Bold;
        textBlock.TextAlignment = TextAlignment.Left;
        textBlock.HorizontalAlignment = HorizontalAlignment.Center;
        textBlock.VerticalAlignment = VerticalAlignment.Stretch;
        textBlock.Margin = new Thickness(35);
        //textBlock.Width = b.PixelWidth - textBlock.Margin.Left * 2;
        textBlock.TextWrapping = TextWrapping.Wrap;
        textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
        textBlock.FontSize = fontsize;

        canvas.Children.Add(textBlock);

        await b.RenderAsync(background);
        await b.RenderAsync(canvas);

        // Get the pixels

        var pixelBuffer = await b.GetPixelsAsync();


        // Get the local folder.
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        // Create a new folder name DataFolder.
        var dataFolder = await local.CreateFolderAsync("DataFolder",
            CreationCollisionOption.OpenIfExists);

        StorageFile file = await dataFolder.CreateFileAsync(imagename, CreationCollisionOption.ReplaceExisting);


        // Encode the image to the selected file on disk
        using (var fileStream = await file.OpenStreamForWriteAsync())
        {

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream.AsRandomAccessStream());

            encoder.SetPixelData(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Ignore,
                (uint)b.PixelWidth,
                (uint)b.PixelHeight,
                DisplayInformation.GetForCurrentView().LogicalDpi,
                DisplayInformation.GetForCurrentView().LogicalDpi,
                pixelBuffer.ToArray());

            await encoder.FlushAsync();
        }
    }
4

2 に答える 2