代码之家  ›  专栏  ›  技术社区  ›  Jambobond

在WPF中放置图标对象

wpf
  •  1
  • Jambobond  · 技术社区  · 14 年前

    我已经实例化了几个system.drawing.icon对象。请注意,这些是在运行时创建的,不会从文件系统存储和加载。我想把这些图像放在我的WPF应用程序中。

    然而,正如我在过去几个小时中发现的,不可能简单地将诸如System.Drawing.Image或图标之类的对象直接添加到画布/堆栈面板,也不可能将System.Windows.Controls.Image的源设置为不存储在文件系统中的图像或图标(在我看来是这样)。

    有什么想法吗?

    1 回复  |  直到 12 年前
        1
  •  1
  •   David    14 年前

    这对我来说很有效,它动态地设置了一个wpf图像,其中包含从动态生成或从磁盘加载的位图中加载的字节:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    using System.IO;
    using System.Drawing.Imaging;
    
    namespace Examples
    {
        public class Util
        {
            private static void SetBitmap(Image imgDest, Bitmap bmpSource)
            {
                byte[] imageBytes;
                using (MemoryStream stream = new MemoryStream())
                {
                    bmpSource.Save(stream, ImageFormat.Png);
    
                    imageBytes = stream.ToArray();
                }
    
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = new MemoryStream(imageBytes);
                bitmapImage.EndInit();
    
                imgDest.Source = bitmapImage;
            }
        }
    }