【WP7】代码创建png图片

windows phone提供了一个  WriteableBitmap 类,该类有一个SaveJpeg方法,可以把控件保存为jpg图片,但是jpeg不支持透明颜色,我们可以利用CodePlex上的ImageTools这个类来创建png格式的图片

http://imagetools.codeplex.com

下载得到  ImageTools.dll  ImageTools.IO.Png.dll  ImageTools.Utils.dll

把三个库引用到项目中

1、创建png图片,保存到隔离存储空间

        private string CreateBackground()
        {
            string tiledirectory = "Shared/ShellContent/Tiles";
            string fullPath = "Shared/ShellContent/Tiles/aa.png";
            //注意:如果该png图片要固定到开始屏幕时,目录必须是Shared/ShellContent/
            
            Grid grid = new Grid
            {
                Background = new ImageBrush
                {
                    ImageSource = new BitmapImage
                    {
                        UriSource = new Uri("/test.png", UriKind.Relative),
                        //这里使用项目中的png图片用于合成
                        CreateOptions = BitmapCreateOptions.IgnoreImageCache
                    }
                },
                Width = 173,
                Height = 173
            };
            
            grid.Arrange(new Rect(0d, 0d, 173, 173));
            WriteableBitmap wbmp = new WriteableBitmap(grid, null);
            
            ExtendedImage extendImage = wbmp.ToImage();

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.DirectoryExists(tiledirectory))
                {
                    store.CreateDirectory(tiledirectory);
                }
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fullPath, FileMode.OpenOrCreate, store))
                {
                    extendImage.WriteToStream(stream, fullPath);
                }
            }
            //保存完成,这里文件保存到    "isostore:/Shared/ShellContent/Tiles/aa.png"
        }

2、下面是使用该png图片

  保存到开始屏幕

        StandardTileData NewTileData = new StandardTileData
        {
            BackgroundImage = new Uri("isostore:/Shared/ShellContent/Tiles/aa.png", UriKind.Absolute)
        };

        ShellTile.Create(new Uri("/MainPage.xaml", UriKind.Relative), NewTileData);

  如果是被控件使用时,要把该文件读取出来,好像不能直接使用该地址的uri

        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream("Shared/ShellContent/Tiles/aa.png", FileMode.Open, store))
            {
                BitmapImage img = new BitmapImage();
                img.SetSource(fs);
                this.image.Source = img;    //赋给Image控件
            }
        }

 https://files.cnblogs.com/bomo/ImageTools.zip

 

posted @ 2013-01-17 20:21  bomo  阅读(826)  评论(5编辑  收藏  举报