Silverlight实用窍门系列:50.InkPresenter涂鸦板的基本使用,以及将效果保存为Png图片【附带源码实例】

简介:

    在Silverlight中我们有时候需要手工绘制线条或者直线等,在这里我们认识一下InkPresenter控件,它将支持用户使用鼠标、手写板等工具来绘制图形或者笔迹,用途为涂鸦、笔迹确认等等。

        InkPresenter是继承于Canvas控件的支持所有的Canvas属性,并且其内部还可以嵌套显示其他控件。InkPresenter控件的显 示分为三层:底层是InkPresenter的Background、中间层是InkPresenter的Children属性的控件、最后才是 Strokes属性中的笔画层。

        对于Strokes属性中的笔画Stroke我们可以设置它的颜色、粗细、外边框颜色等等属性以获得满意的笔画类型。下面我们来看看如何使用InkPresenter控件,首先我们来看Xaml代码如下:

 


 
 
  1. <Grid x:Name="LayoutRoot1" Background="White"> 
  2.     <Canvas> 
  3.         <Border BorderThickness="1" Margin="50 10 0 0" BorderBrush="CadetBlue"  
  4.                 HorizontalAlignment="Center" VerticalAlignment="Center"> 
  5.             <InkPresenter x:Name="iPresenter" Height="500" Width="500" 
  6.               MouseLeftButtonDown="iPresenter_MouseLeftButtonDown"  
  7.               LostMouseCapture="iPresenter_LostMouseCapture"  
  8.               MouseMove="iPresenter_MouseMove"  
  9.               Background="Transparent" Opacity="1" > 
  10.                 <TextBox Width="138" Canvas.Left="58" Canvas.Top="105"></TextBox> 
  11.             </InkPresenter> 
  12.         </Border> 
  13.         <Button Canvas.Left="560" Canvas.Top="11" Content="将涂鸦保存为图片" Height="23" 
  14.                 Name="button1" Width="104" Click="button1_Click" /> 
  15.         <Image Name="showIP" Width="400" Height="400" Canvas.Left="560" Canvas.Top="60"></Image> 
  16.     </Canvas> 
  17. </Grid> 

        然后我们来看看Xaml.cs代码如下:

 


 
 
  1. public partial class MainPage : UserControl 
  2. { 
  3.     public MainPage() 
  4.     { 
  5.         InitializeComponent(); 
  6.         SetPresenterClip(); 
  7.     } 
  8.     Stroke myStroke; 
  9.  
  10.     private void iPresenter_MouseLeftButtonDown(object sender, MouseEventArgs e) 
  11.     { 
  12.         //让鼠标捕获数据 
  13.         iPresenter.CaptureMouse(); 
  14.         //收集笔触数据点保存值StylusPointCollection集合中 
  15.         StylusPointCollection stylusPointCollection = new StylusPointCollection(); 
  16.         stylusPointCollection.Add(e.StylusDevice.GetStylusPoints(iPresenter)); 
  17.         //将数据点的结合保存为一个笔画 
  18.         myStroke = new Stroke(stylusPointCollection); 
  19.         //设置笔画的绘画效果,如颜色,大小等。 
  20.         myStroke.DrawingAttributes.Color = Colors.Gray; 
  21.         myStroke.DrawingAttributes.Width = 1; 
  22.         myStroke.DrawingAttributes.Height = 1; 
  23.         iPresenter.Strokes.Add(myStroke); 
  24.     } 
  25.  
  26.     private void iPresenter_MouseMove(object sender, MouseEventArgs e) 
  27.     { 
  28.         //在鼠标移动的过程中将数据点加入到笔画中去。 
  29.         if (myStroke != null) 
  30.             myStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(iPresenter)); 
  31.     } 
  32.  
  33.     private void iPresenter_LostMouseCapture(object sender, MouseEventArgs e) 
  34.     { 
  35.         //将笔画清空 
  36.         myStroke = null; 
  37.         iPresenter.ReleaseMouseCapture();//释放鼠标坐标 
  38.     } 
  39.  
  40.     /// <summary> 
  41.     /// 设置绘画区域为InkPresenter的大小 
  42.     /// </summary> 
  43.     private void SetPresenterClip() 
  44.     { 
  45.         RectangleGeometry MyRectangleGeometry = new RectangleGeometry(); 
  46.         MyRectangleGeometry.Rect = new Rect(0, 0, iPresenter.ActualWidth, iPresenter.ActualHeight); 
  47.         //设置获取绘画内容的有效区域 
  48.         iPresenter.Clip = MyRectangleGeometry; 
  49.     } 
  50.  
  51.     private void button1_Click(object sender, RoutedEventArgs e) 
  52.     { 
  53.         //保存InkPresenter涂鸦板内绘画的图 
  54.         WriteableBitmap _bitmap = new WriteableBitmap(iPresenter, null); 
  55.         this.showIP.Source = _bitmap; 
  56.         SaveFileDialog sfd = new SaveFileDialog(); 
  57.         sfd.Filter = "PNG Files (*.png)|*.png|All Files (*.*)|*.*"; 
  58.         sfd.DefaultExt = ".png"; 
  59.         sfd.FilterIndex = 1; 
  60.  
  61.         if ((bool)sfd.ShowDialog()) 
  62.         { 
  63.             using (Stream fs = sfd.OpenFile()) 
  64.             { 
  65.                 int width = _bitmap.PixelWidth; 
  66.                 int height = _bitmap.PixelHeight; 
  67.  
  68.                 EditableImage ei = new EditableImage(width, height); 
  69.  
  70.                 for (int i = 0; i < height; i++) 
  71.                 { 
  72.                     for (int j = 0; j < width; j++) 
  73.                     { 
  74.                         int pixel = _bitmap.Pixels[(i * width) + j]; 
  75.                         ei.SetPixel(j, i, 
  76.                                     (byte)((pixel >> 16) & 0xFF), 
  77.                                     (byte)((pixel >> 8) & 0xFF), 
  78.                                     (byte)(pixel & 0xFF), 
  79.                                     (byte)((pixel >> 24) & 0xFF) 
  80.                         ); 
  81.                     } 
  82.                 } 
  83.                 //获取流 
  84.                 Stream png = ei.GetStream(); 
  85.                 int len = (int)png.Length; 
  86.                 byte[] bytes = new byte[len]; 
  87.                 png.Read(bytes, 0, len); 
  88.                 fs.Write(bytes, 0, len); 
  89.                 MessageBox.Show("图片保存成功!"); 
  90.             } 
  91.         } 
  92.  
  93.     } 
  94. } 

        对于将InkPresenter中绘画出来的图片保存为Png图片得处理,我们在这里借鉴了园子中永恒的记忆兄弟的将元素转为Png图片的方法,在这里贴出两个辅助转Png格式的类。

 


 
 
  1. /// <summary> 
  2. /// 编辑图片 
  3. /// </summary> 
  4. public class EditableImage 
  5. { 
  6.     private int _width = 0; 
  7.     private int _height = 0; 
  8.     private bool _init = false; 
  9.     private byte[] _buffer; 
  10.     private int _rowLength; 
  11.  
  12.     /// <summary> 
  13.     /// 当图片错误时引发 
  14.     /// </summary> 
  15.     public event EventHandler<EditableImageErrorEventArgs> ImageError; 
  16.  
  17.     /// <summary> 
  18.     /// 实例化 
  19.     /// </summary> 
  20.     /// <param name="width"></param> 
  21.     /// <param name="height"></param> 
  22.     public EditableImage(int width, int height) 
  23.     { 
  24.         this.Width = width; 
  25.         this.Height = height; 
  26.     } 
  27.  
  28.     public int Width 
  29.     { 
  30.         get 
  31.         { 
  32.             return _width; 
  33.         } 
  34.         set 
  35.         { 
  36.             if (_init) 
  37.             { 
  38.                 OnImageError("错误: 图片初始化后不可以改变宽度"); 
  39.             } 
  40.             else if ((value <= 0) || (value > 2047)) 
  41.             { 
  42.                 OnImageError("错误: 宽度必须在 0 到 2047"); 
  43.             } 
  44.             else 
  45.             { 
  46.                 _width = value; 
  47.             } 
  48.         } 
  49.     } 
  50.  
  51.     public int Height 
  52.     { 
  53.         get 
  54.         { 
  55.             return _height; 
  56.         } 
  57.         set 
  58.         { 
  59.             if (_init) 
  60.             { 
  61.                 OnImageError("错误: 图片初始化后不可以改变高度"); 
  62.             } 
  63.             else if ((value <= 0) || (value > 2047)) 
  64.             { 
  65.                 OnImageError("错误: 高度必须在 0 到 2047"); 
  66.             } 
  67.             else 
  68.             { 
  69.                 _height = value; 
  70.             } 
  71.         } 
  72.     } 
  73.  
  74.     public void SetPixel(int col, int row, Color color) 
  75.     { 
  76.         SetPixel(col, row, color.R, color.G, color.B, color.A); 
  77.     } 
  78.  
  79.     public void SetPixel(int col, int row, byte red, byte green, byte blue, byte alpha) 
  80.     { 
  81.         if (!_init) 
  82.         { 
  83.             _rowLength = _width * 4 + 1; 
  84.             _buffer = new byte[_rowLength * _height]; 
  85.  
  86.             // Initialize 
  87.             for (int idx = 0; idx < _height; idx++) 
  88.             { 
  89.                 _buffer[idx * _rowLength] = 0;      // Filter bit 
  90.             } 
  91.  
  92.             _init = true; 
  93.         } 
  94.  
  95.         if ((col > _width) || (col < 0)) 
  96.         { 
  97.             OnImageError("Error: Column must be greater than 0 and less than the Width"); 
  98.         } 
  99.         else if ((row > _height) || (row < 0)) 
  100.         { 
  101.             OnImageError("Error: Row must be greater than 0 and less than the Height"); 
  102.         } 
  103.  
  104.         // Set the pixel 
  105.         int start = _rowLength * row + col * 4 + 1; 
  106.         _buffer[start] = red; 
  107.         _buffer[start + 1] = green; 
  108.         _buffer[start + 2] = blue; 
  109.         _buffer[start + 3] = alpha; 
  110.     } 
  111.  
  112.     public Color GetPixel(int col, int row) 
  113.     { 
  114.         if ((col > _width) || (col < 0)) 
  115.         { 
  116.             OnImageError("Error: Column must be greater than 0 and less than the Width"); 
  117.         } 
  118.         else if ((row > _height) || (row < 0)) 
  119.         { 
  120.             OnImageError("Error: Row must be greater than 0 and less than the Height"); 
  121.         } 
  122.  
  123.         Color color = new Color(); 
  124.         int _base = _rowLength * row + col + 1; 
  125.  
  126.         color.R = _buffer[_base]; 
  127.         color.G = _buffer[_base + 1]; 
  128.         color.B = _buffer[_base + 2]; 
  129.         color.A = _buffer[_base + 3]; 
  130.  
  131.         return color; 
  132.     } 
  133.  
  134.     public Stream GetStream() 
  135.     { 
  136.         Stream stream; 
  137.  
  138.         if (!_init) 
  139.         { 
  140.             OnImageError("Error: Image has not been initialized"); 
  141.             stream = null; 
  142.         } 
  143.         else 
  144.         { 
  145.             stream = PngEncoder.Encode(_buffer, _width, _height); 
  146.         } 
  147.  
  148.         return stream; 
  149.     } 
  150.  
  151.     private void OnImageError(string msg) 
  152.     { 
  153.         if (null != ImageError) 
  154.         { 
  155.             EditableImageErrorEventArgs args = new EditableImageErrorEventArgs(); 
  156.             args.ErrorMessage = msg; 
  157.             ImageError(this, args); 
  158.         } 
  159.     } 
  160.  
  161.     public class EditableImageErrorEventArgs : EventArgs 
  162.     { 
  163.         private string _errorMessage = string.Empty; 
  164.  
  165.         public string ErrorMessage 
  166.         { 
  167.             get { return _errorMessage; } 
  168.             set { _errorMessage = value; } 
  169.         } 
  170.     } 
  171.  
  172. } 

        这是Png操作类:

 


 
 
  1. /// <summary> 
  2. /// PNG格式操作类 
  3. /// </summary> 
  4. public class PngEncoder 
  5. { 
  6.     private const int _ADLER32_BASE = 65521; 
  7.     private const int _MAXBLOCK = 0xFFFF; 
  8.     private static byte[] _HEADER = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; 
  9.     private static byte[] _IHDR = { (byte)'I', (byte)'H', (byte)'D', (byte)'R' }; 
  10.     private static byte[] _GAMA = { (byte)'g', (byte)'A', (byte)'M', (byte)'A' }; 
  11.     private static byte[] _IDAT = { (byte)'I', (byte)'D', (byte)'A', (byte)'T' }; 
  12.     private static byte[] _IEND = { (byte)'I', (byte)'E', (byte)'N', (byte)'D' }; 
  13.     private static byte[] _4BYTEDATA = { 0, 0, 0, 0 }; 
  14.     private static byte[] _ARGB = { 0, 0, 0, 0, 0, 0, 0, 0, 8, 6, 0, 0, 0 }; 
  15.  
  16.     /// <summary> 
  17.     /// 编码 
  18.     /// </summary> 
  19.     /// <param name="data"></param> 
  20.     /// <param name="width"></param> 
  21.     /// <param name="height"></param> 
  22.     /// <returns></returns> 
  23.     public static Stream Encode(byte[] data, int width, int height) 
  24.     { 
  25.         MemoryStream ms = new MemoryStream(); 
  26.         byte[] size; 
  27.  
  28.         // Write PNG header 
  29.         ms.Write(_HEADER, 0, _HEADER.Length); 
  30.  
  31.         // Write IHDR 
  32.         //  Width:              4 bytes 
  33.         //  Height:             4 bytes 
  34.         //  Bit depth:          1 byte 
  35.         //  Color type:         1 byte 
  36.         //  Compression method: 1 byte 
  37.         //  Filter method:      1 byte 
  38.         //  Interlace method:   1 byte 
  39.  
  40.         size = BitConverter.GetBytes(width); 
  41.         _ARGB[0] = size[3]; _ARGB[1] = size[2]; _ARGB[2] = size[1]; _ARGB[3] = size[0]; 
  42.  
  43.         size = BitConverter.GetBytes(height); 
  44.         _ARGB[4] = size[3]; _ARGB[5] = size[2]; _ARGB[6] = size[1]; _ARGB[7] = size[0]; 
  45.  
  46.         // Write IHDR chunk 
  47.         WriteChunk(ms, _IHDR, _ARGB); 
  48.  
  49.         // Set gamma = 1 
  50.         size = BitConverter.GetBytes(1 * 100000); 
  51.         _4BYTEDATA[0] = size[3]; _4BYTEDATA[1] = size[2]; _4BYTEDATA[2] = size[1]; _4BYTEDATA[3] = size[0]; 
  52.  
  53.         // Write gAMA chunk 
  54.         WriteChunk(ms, _GAMA, _4BYTEDATA); 
  55.  
  56.         // Write IDAT chunk 
  57.         uint widthLength = (uint)(width * 4) + 1; 
  58.         uint dcSize = widthLength * (uint)height; 
  59.  
  60.         // First part of ZLIB header is 78 1101 1010 (DA) 0000 00001 (01) 
  61.         // ZLIB info 
  62.         // 
  63.         // CMF Byte: 78 
  64.         //  CINFO = 7 (32K window size) 
  65.         //  CM = 8 = (deflate compression) 
  66.         // FLG Byte: DA 
  67.         //  FLEVEL = 3 (bits 6 and 7 - ignored but signifies max compression) 
  68.         //  FDICT = 0 (bit 5, 0 - no preset dictionary) 
  69.         //  FCHCK = 26 (bits 0-4 - ensure CMF*256+FLG / 31 has no remainder) 
  70.         // Compressed data 
  71.         //  FLAGS: 0 or 1 
  72.         //    00000 00 (no compression) X (X=1 for last block, 0=not the last block) 
  73.         //    LEN = length in bytes (equal to ((width*4)+1)*height 
  74.         //    NLEN = one's compliment of LEN 
  75.         //    Example: 1111 1011 1111 1111 (FB), 0000 0100 0000 0000 (40) 
  76.         //    Data for each line: 0 [RGBA] [RGBA] [RGBA] ... 
  77.         //    ADLER32 
  78.  
  79.         uint adler = ComputeAdler32(data); 
  80.         MemoryStream comp = new MemoryStream(); 
  81.  
  82.         // 64K的块数计算 
  83.         uint rowsPerBlock = _MAXBLOCK / widthLength; 
  84.         uint blockSize = rowsPerBlock * widthLength; 
  85.         uint blockCount; 
  86.         ushort length; 
  87.         uint remainder = dcSize; 
  88.  
  89.         if ((dcSize % blockSize) == 0) 
  90.         { 
  91.             blockCount = dcSize / blockSize; 
  92.         } 
  93.         else 
  94.         { 
  95.             blockCount = (dcSize / blockSize) + 1; 
  96.         } 
  97.  
  98.         // 头部 
  99.         comp.WriteByte(0x78); 
  100.         comp.WriteByte(0xDA); 
  101.  
  102.         for (uint blocks = 0; blocks < blockCount; blocks++) 
  103.         { 
  104.             // 长度 
  105.             length = (ushort)((remainder < blockSize) ? remainder : blockSize); 
  106.  
  107.             if (length == remainder) 
  108.             { 
  109.                 comp.WriteByte(0x01); 
  110.             } 
  111.             else 
  112.             { 
  113.                 comp.WriteByte(0x00); 
  114.             } 
  115.  
  116.             comp.Write(BitConverter.GetBytes(length), 0, 2); 
  117.  
  118.             comp.Write(BitConverter.GetBytes((ushort)~length), 0, 2); 
  119.  
  120.             // Write 块 
  121.             comp.Write(data, (int)(blocks * blockSize), length); 
  122.  
  123.             //下一块 
  124.             remainder -= blockSize; 
  125.         } 
  126.  
  127.         WriteReversedBuffer(comp, BitConverter.GetBytes(adler)); 
  128.         comp.Seek(0, SeekOrigin.Begin); 
  129.  
  130.         byte[] dat = new byte[comp.Length]; 
  131.         comp.Read(dat, 0, (int)comp.Length); 
  132.  
  133.         WriteChunk(ms, _IDAT, dat); 
  134.  
  135.         // Write IEND chunk 
  136.         WriteChunk(ms, _IEND, new byte[0]); 
  137.  
  138.         // Reset stream 
  139.         ms.Seek(0, SeekOrigin.Begin); 
  140.  
  141.         return ms; 
  142.     } 
  143.  
  144.     private static void WriteReversedBuffer(Stream stream, byte[] data) 
  145.     { 
  146.         int size = data.Length; 
  147.         byte[] reorder = new byte[size]; 
  148.  
  149.         for (int idx = 0; idx < size; idx++) 
  150.         { 
  151.             reorder[idx] = data[size - idx - 1]; 
  152.         } 
  153.         stream.Write(reorder, 0, size); 
  154.     } 
  155.  
  156.     private static void WriteChunk(Stream stream, byte[] type, byte[] data) 
  157.     { 
  158.         int idx; 
  159.         int size = type.Length; 
  160.         byte[] buffer = new byte[type.Length + data.Length]; 
  161.  
  162.         // 初始化缓冲 
  163.         for (idx = 0; idx < type.Length; idx++) 
  164.         { 
  165.             buffer[idx] = type[idx]; 
  166.         } 
  167.  
  168.         for (idx = 0; idx < data.Length; idx++) 
  169.         { 
  170.             buffer[idx + size] = data[idx]; 
  171.         } 
  172.  
  173.         WriteReversedBuffer(stream, BitConverter.GetBytes(data.Length)); 
  174.  
  175.         // Write 类型和数据 
  176.         stream.Write(buffer, 0, buffer.Length);   // Should always be 4 bytes 
  177.  
  178.         // 计算和书写的CRC 
  179.  
  180.         WriteReversedBuffer(stream, BitConverter.GetBytes(GetCRC(buffer))); 
  181.     } 
  182.  
  183.     private static uint[] _crcTable = new uint[256]; 
  184.     private static bool _crcTableComputed = false; 
  185.  
  186.     private static void MakeCRCTable() 
  187.     { 
  188.         uint c; 
  189.  
  190.         for (int n = 0; n < 256; n++) 
  191.         { 
  192.             c = (uint)n; 
  193.             for (int k = 0; k < 8; k++) 
  194.             { 
  195.                 if ((c & (0x00000001)) > 0) 
  196.                     c = 0xEDB88320 ^ (c >> 1); 
  197.                 else 
  198.                     c = c >> 1; 
  199.             } 
  200.             _crcTable[n] = c; 
  201.         } 
  202.  
  203.         _crcTableComputed = true; 
  204.     } 
  205.  
  206.     private static uint UpdateCRC(uint crc, byte[] buf, int len) 
  207.     { 
  208.         uint c = crc; 
  209.  
  210.         if (!_crcTableComputed) 
  211.         { 
  212.             MakeCRCTable(); 
  213.         } 
  214.  
  215.         for (int n = 0; n < len; n++) 
  216.         { 
  217.             c = _crcTable[(c ^ buf[n]) & 0xFF] ^ (c >> 8); 
  218.         } 
  219.  
  220.         return c; 
  221.     } 
  222.  
  223.     //返回的字节的CRC缓冲区 
  224.     private static uint GetCRC(byte[] buf) 
  225.     { 
  226.         return UpdateCRC(0xFFFFFFFF, buf, buf.Length) ^ 0xFFFFFFFF; 
  227.     } 
  228.  
  229.     private static uint ComputeAdler32(byte[] buf) 
  230.     { 
  231.         uint s1 = 1; 
  232.         uint s2 = 0; 
  233.         int length = buf.Length; 
  234.  
  235.         for (int idx = 0; idx < length; idx++) 
  236.         { 
  237.             s1 = (s1 + (uint)buf[idx]) % _ADLER32_BASE; 
  238.             s2 = (s2 + s1) % _ADLER32_BASE; 
  239.         } 
  240.  
  241.         return (s2 << 16) + s1; 
  242.     } 
  243. } 

        最后我们来看看运行的效果如下,如需源码请点击 SLInkPresenter.zip下载:

 

本文转自程兴亮 51CTO博客,原文链接:http://blog.51cto.com/chengxingliang/826757



相关文章