Commit bc3185c8 authored by 潘栩锋's avatar 潘栩锋 🚴

测试 chartToImage ,失败了。。。 binding 不起作用

parent 93fa5687
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>
......@@ -2,7 +2,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="WdSectionsCollectionTest.xaml">
StartupUri="CharttoImage/ChartToImageSample2.xaml">
<Application.Resources>
</Application.Resources>
......
<Window x:Class="WpfApp1.CharttoImage.ChartToImageSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1.CharttoImage"
mc:Ignorable="d"
Title="ChartToImageSample" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<local:ScanGraph x:Name="scanGraph" />
<StackPanel Grid.Row="1" Orientation="Horizontal" >
<Button Content="导出当前" Margin="5" Padding="10,5" Click="btnOutput1Click"/>
<Button Content="导出后台" Margin="5" Padding="10,5" Click="btnOutput2Click"/>
</StackPanel>
</Grid>
</Window>
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp1.CharttoImage
{
/// <summary>
/// ChartToImageSample.xaml 的交互逻辑
/// </summary>
public partial class ChartToImageSample : Window
{
ScanGraphVm scanGraphVm;
public ChartToImageSample()
{
InitializeComponent();
scanGraphVm = new ScanGraphVm();
scanGraph.DataContext = scanGraphVm;
}
private void btnOutput1Click(object sender, RoutedEventArgs e)
{
string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = strDesktopPath;
sfd.Filter = "jpg|*.jpg";
sfd.FileName = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), ".jpg");
if (sfd.ShowDialog() == true)
{
SaveToJpeg(scanGraph, sfd.FileName);
}
}
private void btnOutput2Click(object sender, RoutedEventArgs e)
{
string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = strDesktopPath;
sfd.Filter = "jpg|*.jpg";
sfd.FileName = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), ".jpg");
if (sfd.ShowDialog() == true)
{
SavePic(sfd.FileName);
}
}
void SavePic(string path)
{
//一定要把 scangraph 放入容器, 且scangraph Left,Top 对齐,margin=0
//不然有黑框
//整个scangraph 的尺寸是 Margin+(Width,Height)
//Margin 是透明,也就是黑色
var viewbox = new Viewbox();
ScanGraph scanGraph = new ScanGraph
{
Width = 1024,
Height = 300,
//HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
//VerticalAlignment = System.Windows.VerticalAlignment.Top,
//Margin = new System.Windows.Thickness()
};
scanGraph.DataContext = scanGraphVm;
viewbox.Child = scanGraph;
viewbox.Measure(scanGraph.RenderSize);
viewbox.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0), scanGraph.RenderSize));
scanGraph.chart.Update(true,true);//强制使 livechart 刷新
viewbox.UpdateLayout();
SaveToJpeg(scanGraph, path);
}
void SaveToJpeg(FrameworkElement visual, string fileName)
{
var encoder = new JpegBitmapEncoder();
EncodeVisual(visual, fileName, encoder);
}
void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName)) encoder.Save(stream);
}
}
}
<Window x:Class="WpfApp1.CharttoImage.ChartToImageSample2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1.CharttoImage"
mc:Ignorable="d"
Title="ChartToImageSample2" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1" Orientation="Horizontal" >
<Button Content="导出后台" Margin="5" Padding="10,5" Click="btnOutput2Click"/>
</StackPanel>
</Grid>
</Window>
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp1.CharttoImage
{
/// <summary>
/// ChartToImageSample.xaml 的交互逻辑
/// </summary>
public partial class ChartToImageSample2 : Window
{
ScanGraphVm scanGraphVm;
Viewbox viewbox;
ScanGraph scanGraph;
public ChartToImageSample2()
{
InitializeComponent();
scanGraphVm = new ScanGraphVm();
viewbox = new Viewbox();
scanGraph = new ScanGraph
{
Width = 1024,
Height = 300
};
scanGraph.DataContext = scanGraphVm;
viewbox.Child = scanGraph;
viewbox.Measure(scanGraph.RenderSize);
viewbox.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0), scanGraph.RenderSize));
scanGraph.chart.Update(true, true);//强制使 livechart 刷新
viewbox.UpdateLayout();
}
private void btnOutput2Click(object sender, RoutedEventArgs e)
{
string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = strDesktopPath;
sfd.Filter = "jpg|*.jpg";
sfd.FileName = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), ".jpg");
if (sfd.ShowDialog() == true)
{
SavePic2(sfd.FileName);
}
}
async void SavePic(string path)
{
//一定要把 scangraph 放入容器, 且scangraph Left,Top 对齐,margin=0
//不然有黑框
//整个scangraph 的尺寸是 Margin+(Width,Height)
//Margin 是透明,也就是黑色
var viewbox = new Viewbox();
ScanGraph scanGraph = new ScanGraph
{
Width = 1024,
Height = 300,
//HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
//VerticalAlignment = System.Windows.VerticalAlignment.Top,
//Margin = new System.Windows.Thickness()
};
scanGraph.DataContext = scanGraphVm;
scanGraph.chart.AxisX[0].SetBinding(LiveCharts.Wpf.Axis.MinValueProperty, new Binding(nameof(scanGraphVm.XMin)) { Source = scanGraphVm });
scanGraph.chart.AxisX[0].SetBinding(LiveCharts.Wpf.Axis.MaxValueProperty, new Binding(nameof(scanGraphVm.XMax)) { Source = scanGraphVm });
scanGraph.chart.AxisY[0].SetBinding(LiveCharts.Wpf.Axis.MinValueProperty, new Binding(nameof(scanGraphVm.YMin)) { Source = scanGraphVm });
scanGraph.chart.AxisY[0].SetBinding(LiveCharts.Wpf.Axis.MaxValueProperty, new Binding(nameof(scanGraphVm.YMax)) { Source = scanGraphVm });
(scanGraph.chart.Series[0] as LiveCharts.Wpf.LineSeries)
.SetBinding(LiveCharts.Wpf.LineSeries.ValuesProperty, new Binding(nameof(scanGraphVm.Values)) { Source = scanGraphVm });
viewbox.Child = scanGraph;
viewbox.Measure(scanGraph.RenderSize);
viewbox.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0), scanGraph.RenderSize));
scanGraph.chart.Update(true,true);//强制使 livechart 刷新
viewbox.UpdateLayout();
//scanGraph.chart.Update(true, true);//强制使 livechart 刷新
//等会再导出
//await Task.Delay(2000);
//scanGraph.chart.Update(true, true);//强制使 livechart 刷新
SaveToJpeg(scanGraph, path);
}
async void SavePic2(string path)
{
scanGraph.chart.Update(true, true);//强制使 livechart 刷新
SaveToJpeg(scanGraph, path);
}
void SaveToJpeg(FrameworkElement visual, string fileName)
{
var encoder = new JpegBitmapEncoder();
EncodeVisual(visual, fileName, encoder);
}
void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName)) encoder.Save(stream);
}
}
}
<UserControl x:Class="WpfApp1.CharttoImage.ScanGraph"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1.CharttoImage" xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Background="White">
<UserControl.Resources>
<local:ScanGraphVm x:Key="viewModel"/>
</UserControl.Resources>
<Grid x:Name="grid_root" d:DataContext="{StaticResource viewModel}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5">
X = [<Run Text="{Binding XMin}"/> ~ <Run Text="{Binding XMax}"/>]
</TextBlock>
<TextBlock Margin="5">
Y = [<Run Text="{Binding YMin}"/> ~ <Run Text="{Binding YMax}"/>]
</TextBlock>
</StackPanel>
<lvc:CartesianChart x:Name="chart" x:FieldModifier="public" Grid.Row="1"
Hoverable="False" DisableAnimations="True" DataTooltip="{x:Null}" Margin="5">
<!--<lvc:CartesianChart.AxisX>
<lvc:Axis x:Name="axisX_0" MaxValue="{Binding XMax}" MinValue="{Binding XMin}"/>
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis x:Name="axisY_0" MaxValue="{Binding YMax}" MinValue="{Binding YMin}" />
</lvc:CartesianChart.AxisY>
<lvc:CartesianChart.Series>
<lvc:LineSeries x:Name="series_0" Values="{Binding Values}"/>
</lvc:CartesianChart.Series>-->
<lvc:CartesianChart.AxisX>
<lvc:Axis x:Name="axisX_0" x:FieldModifier="public" MaxValue="{Binding XMax}" MinValue="{Binding XMin}" />
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis x:Name="axisY_0" x:FieldModifier="public" MaxValue="{Binding YMax}" MinValue="{Binding YMin}" />
</lvc:CartesianChart.AxisY>
<lvc:CartesianChart.Series>
<lvc:LineSeries x:Name="series_0" x:FieldModifier="public" Values="{Binding Values}" />
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</Grid>
</UserControl>
using LiveCharts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1.CharttoImage
{
/// <summary>
/// ScanGraph.xaml 的交互逻辑
/// </summary>
public partial class ScanGraph : UserControl
{
public ScanGraph()
{
InitializeComponent();
}
/// <summary>
/// The minimum value property
/// </summary>
public static readonly DependencyProperty MinValueProperty = DependencyProperty.Register(
nameof(MinValue), typeof(double), typeof(ScanGraph),
new PropertyMetadata(double.NaN));
/// <summary>
/// Gets or sets axis min value, set it to double.NaN to make this property Auto, default value is double.NaN
/// </summary>
public double MinValue
{
get { return (double)GetValue(MinValueProperty); }
set { SetValue(MinValueProperty, value); }
}
}
public class ScanGraphVm : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public double XMax { get; set; } = double.NaN;
public double XMin { get; set; } = double.NaN;
public double YMax { get; set; } = double.NaN;
public double YMin { get; set; } = double.NaN;
public ChartValues<double> Values { get; } = new ChartValues<double>();
public ScanGraphVm()
{
XMax = 150;
XMin = 50;
YMax = 20;
YMin = -10;
Random random = new Random();
double target = 10;
List<double> values = new List<double>();
for (int i = 0; i < 200; i++) {
values.Add((random.NextDouble() - 0.5) * 5 + target);
}
Values.AddRange(values);
}
}
}
......@@ -19,7 +19,7 @@ namespace WpfApp1.Properties {
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
......
......@@ -12,7 +12,7 @@ namespace WpfApp1.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
......
......@@ -8,7 +8,7 @@
<OutputType>WinExe</OutputType>
<RootNamespace>WpfApp1</RootNamespace>
<AssemblyName>WpfApp1</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
......@@ -58,6 +58,15 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="CharttoImage\ChartToImageSample2.xaml.cs">
<DependentUpon>ChartToImageSample2.xaml</DependentUpon>
</Compile>
<Compile Include="CharttoImage\ChartToImageSample.xaml.cs">
<DependentUpon>ChartToImageSample.xaml</DependentUpon>
</Compile>
<Compile Include="CharttoImage\ScanGraph.xaml.cs">
<DependentUpon>ScanGraph.xaml</DependentUpon>
</Compile>
<Compile Include="Column2Example.xaml.cs">
<DependentUpon>Column2Example.xaml</DependentUpon>
</Compile>
......@@ -67,6 +76,18 @@
<Compile Include="WdSectionsCollectionTest.xaml.cs">
<DependentUpon>WdSectionsCollectionTest.xaml</DependentUpon>
</Compile>
<Page Include="CharttoImage\ChartToImageSample2.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="CharttoImage\ChartToImageSample.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="CharttoImage\ScanGraph.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Column2Example.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment