gpt4 book ai didi

c# - 从 WPF System.Windows.Shapes.Path 创建图像

转载 作者:行者123 更新时间:2023-11-30 22:06:32 30 4
gpt4 key购买 nike

我有一条路。它在 ContentControl 中正确显示:

<ContentControl
Name="PathContainer"
Content="{Binding Path}"
RenderTransform="{StaticResource ScaleTransform}"
Width="Auto"
Height="Auto"
Background="Transparent"
/>

但我想将其复制到剪贴板。下面创建了一个看似正确大小的纯黑色位图。如果我将画笔更改为白色,它会创建一个正确大小的纯白色位图。如果不是创建此 Canvas,而是从在 UI 中托管 Path 的实际 ContentControl 进行渲染,我会得到正确的位图大小,上面绘制了 Path,但背景似乎是不透明的黑色(除非我将背景更改为 PapayaWhip 或其他东西,它可以满足您的需求预计)。

当我说“似乎是一个不透明的黑色背景”时,我的意思是当我使用 System.Windows.Clipboard.CopyImage() 将它复制到剪贴板并将其粘贴到 VS 图标中时或位图编辑器,粘贴图像的背景是黑色而不是透明的,应该是半透明的抗锯齿像素是它们在黑色背景上看起来的颜色。

那么,两个问题:

第一:下面的代码是坏了,还是我只是想做一些你做不到的事情?它不会抛出任何异常,WPF 中的 FWIW。

第二:在WPF中如何制作带alpha channel 的位图?我是否应该停止将时间浪费在所有这些省力的抽象上,重新编写一个 BITMAPINFOHEADER,并在循环中手动创建 ARGB 四边形?

public BitmapSource CreateImage(Transform tfm)
{
var path = CreatePath();

var rcBounds = path.Data.GetRenderBounds(GetPen());

if (null != tfm)
{
rcBounds = tfm.TransformBounds(rcBounds);
}

int pxWidth = (int)Math.Round(rcBounds.Width);
int pxHeight = (int)Math.Round(rcBounds.Height);

var canvas = new System.Windows.Controls.Canvas();

canvas.Width = pxWidth;
canvas.Height = pxHeight;
canvas.Margin = new System.Windows.Thickness(0);
canvas.Background = Brushes.Transparent;

canvas.Measure(new Size(canvas.Width, canvas.Height));
canvas.Arrange(new Rect(new Size(canvas.Width, canvas.Height)));
canvas.UpdateLayout();

canvas.Children.Add(path);

canvas.RenderTransform = tfm;

RenderTargetBitmap rtb = new RenderTargetBitmap(pxWidth, pxHeight,
96, 96, PixelFormats.Pbgra32);

rtb.Render(canvas);

return BitmapFrame.Create(rtb);
}

最佳答案

Canvas好像没必要。您可以直接将路径渲染到 RenderTargetBitmap 中,例如以下具有透明背景的蓝色圆圈:

var path = new Path
{
Data = new EllipseGeometry(new Point(100, 100), 100, 100),
Fill = Brushes.Blue
};

var bounds = path.Data.GetRenderBounds(null);
path.Measure(bounds.Size);
path.Arrange(bounds);

var bitmap = new RenderTargetBitmap(
(int)bounds.Width, (int)bounds.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(path);

关于c# - 从 WPF System.Windows.Shapes.Path 创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582237/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com