Code :
private void Foo(Canvas canvas)
{
// The content is a bit larger...
Size size = new Size(canvas.ActualWidth * 1.1, canvas.ActualHeight * 1.2);
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96d,
96d,
PixelFormats.Pbgra32
);
renderBitmap.Render(canvas);
// Then copy to clipboard
Clipboard.SetImage(renderBitmap);
}
我需要的 :
将具有透明背景的画布渲染为图像,然后将其复制到剪贴板(很简单?不是真的)
问题 :
粘贴时,我得到一个黑色背景的丑陋图像
解决方案1:
canvas.Background = new SolidColorBrush(Colors.White);
不行。这么厚不行,背景canvas
未来不会改变renderBitmap.Render(canvas);
相反,我必须使用计时器,给 WPF 一些时间来更改背景,然后在该计时器的滴答事件中渲染它。它有效,但不幸的是,内容canvas
比它的尺寸大......所以白色背景只能覆盖它的一部分,结果仍然丑陋。
(顺便说一句,有人知道为什么需要一些时间来改变背景吗?我认为它应该立即改变)
我做错什么了吗?如何在剪贴板中获取白色背景前透明图像?
更重要的是,我注意到,如果将某些 PNG 图像粘贴到不支持 Alpha 通道的 mspaint.exe 中,其背景会保持白色,但其他一些图像会变成黑色。
有没有类似的东西,比如说,alternative color
,如果您粘贴图像的地方不支持 Alpha 通道,则将其用作背景?我们可以定制吗?
现在我渲染了另一个BitmapSource
与白色内容,如果有办法将其与渲染位图作为背景,问题解决了,但我不知道如何......
int dWidth = (int)size.Width;
int dHeight = (int)size.Height;
int dStride = dWidth * 4;
byte[] pixels = new byte[dHeight * dStride];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = 0xFF;
}
BitmapSource bg = BitmapSource.Create(
dWidth,
dHeight,
96,
96,
PixelFormats.Pbgra32,
null,
pixels,
dStride
);
// Combine bg with renderBitmap