Note that there are some explanatory texts on larger screens.

plurals
  1. POCopy image with alpha channel to clipboard with custom background color?
    primarykey
    data
    text
    <p><strong>Code :</strong></p> <pre><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); } </code></pre> <p><strong>What I need :</strong></p> <p>Render a canvas with transparent background to image, then copy it to clipboard (Quit simple? Not really)</p> <p><strong>Problem :</strong></p> <p>When paste, I get a ugly image with black background</p> <p><strong>Solution 1 :</strong></p> <pre><code>canvas.Background = new SolidColorBrush(Colors.White); </code></pre> <p>No. This thick do not work, the background of <code>canvas</code> will not change in the next <code>renderBitmap.Render(canvas);</code></p> <p>Instead, I have to use a timer, give WPF some time to change the background, then render it in the tick event of that timer. It works, but unfortunately, the content of <code>canvas</code> is larger than it's size...so the white background can only cover part of it, still ugly result. (BTW anyone know why it takes sometime to change the background? I thought it should be changed instantly)</p> <p>Did I do something wrong? How can I get a white background ex-transparent image in clipboard?</p> <p>What's more, I've noticed that the background of some PNG images remain white if you paste it into mspaint.exe which do not support alpha channel, but some others become black.</p> <p>Is there something like, say, <code>alternative color</code>, which is used as background if the place where you paste your image do not support alpha channel? Can we custom it?</p> <p>Now I rendered another <code>BitmapSource</code> with white content, if there is a way to combine it with the <em>renderBitmap</em> as background, the problem solved, but I don't know how...</p> <pre><code>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 &lt; pixels.Length; i++) { pixels[i] = 0xFF; } BitmapSource bg = BitmapSource.Create( dWidth, dHeight, 96, 96, PixelFormats.Pbgra32, null, pixels, dStride ); // Combine bg with renderBitmap </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload