0

Есть WPF приложении, с Grid которого нужно снять изображение. Т.е. не скриншот области на которой находится грид а именно изображение Grid. Использую такой метод:

private void ImgScreenSchots(Grid OScreen)
{
    int Width = (int)OScreen.RenderSize.Width;
    int Heith = (int)OScreen.RenderSize.Height;
    RenderTargetBitmap renderTargetBitmap =  new RenderTargetBitmap(Width, Heith, 96, 96, PixelFormats.Default);
    renderTargetBitmap.Render(OScreen);
    PngBitmapEncoder pngImage = new PngBitmapEncoder();
    pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
    using (Stream fileStream = File.Create(Environment.CurrentDirectory + "GridIMG.png"))
    {
        pngImage.Save(fileStream);
    }
}

В результате сохраняет пустой файл размером 1кб. В чем тут ошибка ?

UPD Возможно дело в структуре грида :

<Grid Grid.Column="4" x:Name="IdealPortfell">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <Grid Background="{StaticResource Gray46}">
        <Label Content="Recomenred Portfolio" Style="{StaticResource StyleHeaderLabel}" />
    </Grid>
    <Border Grid.Row="1" BorderBrush="{StaticResource Gray36}" BorderThickness="1">
        <Grid Margin="20">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="2*"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="2*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Button></Button>
            <syncfusion:SfChart x:Name="multipleDoughnutChart2" AreaBorderThickness="0" Grid.RowSpan="3" Grid.ColumnSpan="3"  >
                <syncfusion:DoughnutSeries x:Name="doughnutSeries" EnableAnimation="True" 
                                   EnableSmartLabels="False" Stroke="#262626" StrokeThickness="1" 
                                   DoughnutCoefficient=".7" DoughnutSize="1" DoughnutHoleSize="0.5"
                                   XBindingPath="Name" YBindingPath="Value" Palette="Custom"
                                   ItemsSource="{Binding DiagrammIdealCollection}">
                    <syncfusion:DoughnutSeries.ColorModel>
                        <syncfusion:ChartColorModel>
                            <syncfusion:ChartColorModel.CustomBrushes>
                                <SolidColorBrush Color="#ff0000"/>
                                <SolidColorBrush Color="#F98E3C"/>
                                <SolidColorBrush Color="#FFC087"/>
                            </syncfusion:ChartColorModel.CustomBrushes>
                        </syncfusion:ChartColorModel>
                    </syncfusion:DoughnutSeries.ColorModel>
                </syncfusion:DoughnutSeries>
            </syncfusion:SfChart>
            <Viewbox VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Row="1" Grid.Column="1">
                <StackPanel>
                    <TextBlock Text="Difference" Style="{StaticResource StyleComment}" HorizontalAlignment="Center" />
                    <TextBlock Text="{Binding idealP}" Style="{StaticResource StyleComment}" HorizontalAlignment="Center" FontSize="30" />
                    <TextBlock Text="Critical" Style="{StaticResource StyleComment}" HorizontalAlignment="Center" />
                </StackPanel>
            </Viewbox>
        </Grid>
    </Border>
</Grid>
10
  • Может быть, грид пустой?
    – VladD
    24 авг 2017 в 17:14
  • @VladD Есть метки, кнопки. Не пустой точно 24 авг 2017 в 17:20
  • А не вызываете ли вы эту функцию в конструкторе?
    – VladD
    24 авг 2017 в 17:20
  • И проверьте размер, равен ли он ожидаемому.
    – VladD
    24 авг 2017 в 17:21
  • @VladD метод вызывается при нажатии не кнопку. 1кб это точно не тот размер который я ожидал ) 24 авг 2017 в 17:23

1 ответ 1

1

Используйте свойства ActualWidth и ActualHeight

private void ImgScreenSchots(Grid oScreen)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int) oScreen.ActualWidth,
        (int) oScreen.ActualHeight, 96, 96, PixelFormats.Default);

    renderTargetBitmap.Render(oScreen);

    PngBitmapEncoder pngImage = new PngBitmapEncoder();
    pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

    using (Stream fileStream = File.Create(Environment.CurrentDirectory + "GridIMG.png"))
    {
        pngImage.Save(fileStream);
    }
}

Для получения ImageSource используйте данный метод.

private ImageSource CreateScreenShoot(FrameworkElement element)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)element.ActualWidth,
        (int)element.ActualHeight, 96, 96, PixelFormats.Default);

    renderTargetBitmap.Render(element);

    return renderTargetBitmap;
}

Пример использования:

Button.Click += (sender, args) =>
{
    SomeImage.Source = CreateScreenShoot(SomeElement);
};

Добавим класс расширяющий данный метод:

public static class Extension
{
    public static System.Drawing.Bitmap ToBitmap(this RenderTargetBitmap source)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(source));
            enc.Save(memoryStream);
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(memoryStream);
            return new Bitmap(bitmap);
        }
    }

    public static System.Drawing.Bitmap ToBitmap(this ImageSource source)
    {
        RenderTargetBitmap temp = source as RenderTargetBitmap;
        if (temp == null)
            throw new NotSupportedException(nameof(source));
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(temp));
            enc.Save(memoryStream);
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(memoryStream);
            return new Bitmap(bitmap);
        }
    }
}

Теперь любой снимок можно преобразовывать в Bitmap

CreateScreenShoot(SomeUIElement).ToBitmap();

Результат многократного нажатия: введите сюда описание изображения

6
  • Спасибо помогло. А есть способ сохранять не в файл а в Bitmap в коде ? 24 авг 2017 в 18:32
  • Да, сейчас дополню ответ
    – user206435
    24 авг 2017 в 18:46
  • А где преобразование в Bitmap ? 24 авг 2017 в 18:55
  • RenderTargetBitmap и Bitmap это одно и то же ? 24 авг 2017 в 19:08
  • @Сергей нет, это разные типы, добавил расширяющий метод в ответ
    – user206435
    24 авг 2017 в 19:19

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.