1

我必须把动态生成的图像

var img = new Bitmap(..);
// draw something on img canvas ...

到 ToggleButton 背景。当我将生成的图像分配给 ToggleButton.Content 属性时,我看到“System.Drawing.Bitmap”字符串,而不是图像本身。看起来 ToString() 方法用于 Content 属性。我怎样才能显示生成的图像?

4

2 回答 2

2

“内容”属性与您在 ToggleButton 的表面上写的内容有关。您需要初始化 UI 元素的“背景”属性。这是一个例子:

        PixelFormat pf = PixelFormats.Bgr32;
        int width = 200;
        int height = 200;
        int rawStride = (width * pf.BitsPerPixel + 7) / 8;
        byte[] rawImage = new byte[rawStride * height];

        // Initialize the image with data.
        Random value = new Random();
        value.NextBytes(rawImage);

        // Create a BitmapSource.
        BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);

        ImageBrush imgBrush = new ImageBrush(bitmap);
        myToggleButton.Background = imgBrush;

我使用以下文章http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource(VS.85).aspx创建了图像

于 2011-01-07T23:45:52.610 回答
2

如果 WPF 没有适当的转换器,它只是调用该ToString()方法,位图格式不合适,您通常要使用Image的源是 a BitmapImage,有几种方法可以在不同格式之间进行转换。
这是一种从Bitmapto转换的方法BitmapImage

public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
    MemoryStream ms = new MemoryStream();
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();

    bImg.BeginInit();
    bImg.StreamSource = new MemoryStream(ms.ToArray());
    bImg.CreateOptions = BitmapCreateOptions.None;
    bImg.CacheOption = BitmapCacheOption.Default;
    bImg.EndInit();

    ms.Close();

    return bImg;
}

请注意,ImageFormat.Png它比未压缩格式慢,但如果有的话,它会保留透明度。
现在您应该能够将其用作 Image 控件的 Source,并将此 Image 控件用作按钮的内容。

于 2011-01-07T23:31:11.190 回答