WPF 引用DLL纯图像资源包类库中的图片

1、建立WPF应用程序
             过程略。
 
2、创建类库项目(图片资源包)
      创建图片资源类库项目MyImages,删除class1.cs,在项目属性的资源选项中选择“图像”类型,并在“添加资源”中点击“添加现有的文件”,把图像加入到资源。并把访问修饰符改为Public。
 
3、在WPF应用程序中引用类库项目
       在WPF中通过 MyImages.Properties.Resources.XXX即可访问图像。XXX为图像文件名(资源名称)。但在WPF中的到图像还需一下工作。
 
4、WPF中创建Rectangle或其它采用ImageBrush对象为填充或背景的控件,将ImageBrush的ImageSource属性设置为资源包中图像的方法如下:
 /// <summary>
        /// 读取符号(图片资源库中的文件)
        /// </summary>
        /// <param name="symbolName"></param>
        /// <returns></returns>
        public static ImageBrush GetImagebrush(string ImageName)
        {
            ImageBrush imageBrush = new ImageBrush();
            System.Resources.ResourceManager rm = ImageLibrary.Properties.Resources.ResourceManager;
            System.Drawing.Bitmap b = (System.Drawing.Bitmap)rm.GetObject(ImageName);
            imageBrush.ImageSource = ToWpfBitmap(b);
            return imageBrush;
        }

      

 public static BitmapSource ToWpfBitmap(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                //注意:转换的图片的原始格式ImageFormat设为BMP、JPG、PNG等
                bitmap.Save(stream, ImageFormat.Png);

                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
                // Force the bitmap to load right now so we can dispose the stream.
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }

            

调用方法:           Rectangle1.Fill=GetImagebrush(ImageName);
     注意转换的图片的原始格式ImageFormat必须设置正确。如原图片为PNG格式,调用时设为BMP格式时会失真。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值