`
jiasongmao
  • 浏览: 648120 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

基于像素的图像合成(For WPF)

    博客分类:
  • WPF
阅读更多

     传统的基于GDI或GDI+的图形开发大家再熟悉不过了,通过Drawing类可以轻松的对位图进行处理,那么在WPF中的Media类是否也拥有同样类似的方法功能呢?这是肯定的。

     本节我以精灵装备合成Show(纸娃娃)为例向大家演示如何在WPF中实现基于像素的图象合成。 首先准备一下合成用的素材:

 

 

接下来是进行绘图的第一步:创建绘图工具实例并开启绘图:

     DrawingVisual drawingVisual = new DrawingVisual();

     DrawingContext drawingContext = drawingVisual.RenderOpen();

接着按深度顺序从底到外逐个对象绘制:

     BitmapSource weapon = GetImage(

string.Format("Image/Weapon_{0}.png",

(comboBox1.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(weapon, new Rect(18, 18, 120, 120));

通过以上代码,我们将位于"Image/Weapon_{0}.png"的武器图片绘制到一个x,y方向偏移量分别为(18,18)的120*120像素的矩形上,其中的GetImage方法为:

        //图片加载

        private BitmapSource GetImage(string uri) {

            try {

                return BitmapFrame.Create(new Uri(string.Format(@"{0}", uri), UriKind.Relative));

            } catch {

                return null;

            }

        }

然后通过相类似的代码再分别依次绘制身体、左手、右手、头部、坐骑等部位:

//绘制身体

     BitmapSource body = GetImage(

string.Format("Image/Body_{0}.png",

(comboBox2.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(body, new Rect(50, 50, 100, 100));

//绘制左手

     BitmapSource LeftHand = GetImage(

string.Format("Image/LeftHand_{0}.png",

(comboBox3.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(LeftHand, new Rect(72, 52, 30, 30));

//绘制右手

     BitmapSource RightHand = GetImage(

string.Format("Image/RightHand_{0}.png",

(comboBox4.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(RightHand, new Rect(98, 59, 30, 30));

//绘制头部

     BitmapSource Head = GetImage(

string.Format("Image/Head_{0}.png",

(comboBox5.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(Head, new Rect(86, 38, 20, 30));

//绘制坐骑

     BitmapSource Horse = GetImage(

string.Format("Image/Horse_{0}.png",

(comboBox6.SelectedItem as ComboBoxItem).Content)

);

     drawingContext.DrawImage(Horse, new Rect(63, 71, 70, 120));

所有对象绘制完后即可以关闭画板并呈现出来:

     drawingContext.Close();

     RenderTargetBitmap composeImage = new RenderTargetBitmap(200, 200, 0, 0, PixelFormats.Pbgra32);

     composeImage.Render(drawingVisual);

最后将composeImage这个合成的图片作为图片源赋值给精灵即完成了整个合成流程:

Spirit.Source = composeImage;

实现后的系统界面如下:

本节以展示如何在WPF中对像素位图进行合成,由于素材资源有限,因此无法为大家演示动画效果的纸娃娃图片合成系统。但是万变不离其中,只要您掌握了本文的方法并合理的处理好图片组的缓存,这将为您的图片合成带来更高的性能与效果。

下一节我将为大家讲解如何在Silverlight中实现一模一样的效果,这就是传说中的移植,敬请关注.

 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/alamiye010/archive/2009/09/20/4572834.aspx

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics