
/*

* WriteableBitmap - 位图 API(Bitmap API)

* WriteableBitmap.Pixels - 一个整型数组,用于描述某像素的颜色(ARGB)

* WriteableBitmap.Render() - 将指定的 UIElement 以位图的方式呈现出来

* WriteableBitmap.Invalidate() - 绘图

* WriteableBitmap.PixelWidth - 宽度。单位:像素

* WriteableBitmap.PixelHeight - 高度。单位:像素

*/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Navigation;

using System.Windows.Media.Imaging;

namespace Silverlight30.Graphic

{

public partial class WriteableBitmapDemo : Page

{

public WriteableBitmapDemo()

{

InitializeComponent();

this.Loaded += new RoutedEventHandler(WriteableBitmapDemo_Loaded);

this.Loaded += new RoutedEventHandler(WriteableBitmapDemo_Loaded2);

}

/// <summary>

/// 以自定义像素点颜色的方式生成位图

/// </summary>

void WriteableBitmapDemo_Loaded( object sender, RoutedEventArgs e)

{

// 初始化一个宽 40 高 20 的 WriteableBitmap 对象

WriteableBitmap bitmap = new WriteableBitmap(40, 30);

for ( int i = 0; i < 40 * 30; i++)

{

unchecked

{

// 每个像素的颜色的描述规范为 ARGB

bitmap.Pixels[i] = ( int)0xFFFF0000;

}

}

bitmap.Invalidate();

img.Source = bitmap;

}

/// <summary>

/// 将指定的 UIElement 以位图的方式做呈现

/// </summary>

void WriteableBitmapDemo_Loaded2( object sender, RoutedEventArgs e)

{

WriteableBitmap bitmap = new WriteableBitmap(320, 240);

var txt = new TextBlock();

txt.Text = "webabcd";

// 将指定的 TextBlock 以位图的方式呈现出来

bitmap.Render(txt, new ScaleTransform() { ScaleX = 320 / txt.ActualWidth, ScaleY = 240 / txt.ActualHeight });

bitmap.Invalidate();

img2.Source = bitmap;

}

/// <summary>

/// 获取指定图片的某像素点的颜色

/// </summary>

private void img3_MouseMove( object sender, MouseEventArgs e)

{

WriteableBitmap bitmap = new WriteableBitmap(img3, null);

int color = bitmap.Pixels[( int)e.GetPosition(img3).Y * ( int)img3.ActualWidth + ( int)e.GetPosition(img3).X];

// 将整型转换为字节数组

byte[] bytes = BitConverter.GetBytes(color);

// 将字节数组转换为颜色(bytes[3] - A, bytes[2] - R, bytes[1] - G, bytes[0] - B)

lbl.Text = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]).ToString();

}

/// <summary>

/// 用 WriteableBitmap 实现对视频文件的截屏功能

/// </summary>

private void Button_Click( object sender, RoutedEventArgs e)

{

// 将指定的 UIElement 转换为 WriteableBitmap 对象

WriteableBitmap bitmap = new WriteableBitmap(mediaElement, null);

img4.Source = bitmap;

}

private void mediaElement_MediaEnded( object sender, RoutedEventArgs e)

{

mediaElement.Stop();

mediaElement.Play();

}

}

}