【问题标题】:Place an Icon Object in WPF在 WPF 中放置一个图标对象
【发布时间】:2010-07-15 15:04:57
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

    标签: wpf


    【解决方案1】:

    这对我有效地动态设置 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;
            }
        }
    }
    

    【讨论】:

    • 嗨,David,谢谢,是的,我之前尝试过类似的方法,但收到“错误 HRESULT E_FAIL 已从对 COM 组件的调用中返回。”尝试“bmpSource.Save”时
    • 得到它的工作,我必须先将我的图标添加到一个好的老式 System.Windows.Forms.ImageList()
    猜你喜欢
    • 1970-01-01
    • 2022-08-24
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2011-05-06
    • 2016-05-29
    相关资源
    最近更新 更多