Skip to content

Commit

Permalink
Add white background for png image. (#367)
Browse files Browse the repository at this point in the history
  • Loading branch information
YukiMatsuzawa authored Jun 6, 2024
1 parent 22d38e9 commit bf3e5d5
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Common/ChartDrawing/IO/CopyImageAsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace CompMs.Graphics.IO
{
public class CopyImageAsCommand : ICommand
{
public static CopyImageAsCommand BitmapInstance { get; } = new CopyImageAsCommand(ImageFormat.Png);
public static CopyImageAsCommand BitmapInstance { get; } = new CopyImageAsCommand(ImageFormat.Png) { Converter = SetBackgroundConverter.White };

public static CopyImageAsCommand EmfInstance { get; } = new CopyImageAsCommand(ImageFormat.Emf);

Expand Down
2 changes: 1 addition & 1 deletion src/Common/ChartDrawing/IO/SaveImageAsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class SaveImageAsCommand : ICommand
{
public static SaveImageAsCommand Instance { get; } = new SaveImageAsCommand();

public static SaveImageAsCommand PngInstance { get; } = new SaveImageAsCommand(ImageFormat.Png);
public static SaveImageAsCommand PngInstance { get; } = new SaveImageAsCommand(ImageFormat.Png) { Converter = SetBackgroundConverter.White };

public static SaveImageAsCommand EmfInstance { get; } = new SaveImageAsCommand(ImageFormat.Emf);

Expand Down
50 changes: 50 additions & 0 deletions src/Common/ChartDrawing/IO/SetBackgroundConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace CompMs.Graphics.IO;

public sealed class SetBackgroundConverter : DependencyObject, IVisualConverter
{
public static readonly DependencyProperty BackgroundProperty =
DependencyProperty.Register(
nameof(Background),
typeof(Brush),
typeof(SetBackgroundConverter),
new PropertyMetadata(Brushes.Transparent));

public Brush Background {
get => (Brush)GetValue(BackgroundProperty);
set => SetValue(BackgroundProperty, value);
}

public FrameworkElement Convert(FrameworkElement element) {
var brush = new VisualBrush(element);
var width = element.ActualWidth;
var height = element.ActualHeight;
var canvas = new Canvas
{
Width = width,
Height = height,
Background = Background,
};

var rectangle = new Rectangle
{
Width = width,
Height = height,
Fill = brush,
};
Canvas.SetTop(rectangle, 0d);
Canvas.SetLeft(rectangle, 0d);

canvas.Children.Add(rectangle);
canvas.Measure(new Size(width, height));
canvas.Arrange(new Rect(0, 0, width, height));

return canvas;
}

public static SetBackgroundConverter White { get; } = new SetBackgroundConverter { Background = Brushes.White };
}

0 comments on commit bf3e5d5

Please sign in to comment.