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格式時會失真。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM