Windows Phone開發(fā)(21):做一個(gè)簡單的繪圖板
其實(shí)我們今天要說的就是一個(gè)控件——InkPresenter,這個(gè)控件并不是十分強(qiáng)大,沒辦法和WPF中的InkCanvas相比,估計(jì)在實(shí)際開發(fā)中也很少可能會(huì)用到它,不過,我們還是來了解一下吧,畢竟用起來也不難。
使用該控件沒有什么技術(shù)含量,注意一下以下幾點(diǎn)就是了:
1、必須明確指定InkPresenter的寬度和高度,也就是不能使用自動(dòng)值和Margin,不然不能收集墨跡,除非里面有子元素;
2、要收集墨跡,要設(shè)置Clip屬性;
3、可以使用DrawingAttributes類設(shè)置墨跡的大小和顏色。
該控件不能像WPF那樣自動(dòng)實(shí)現(xiàn)收集墨跡的功能,也就是說只能是我們自己寫代碼了。
- <Grid>
- <InkPresenter x:Name="MyPresenter"
- HorizontalAlignment="Left"
- VerticalAlignment="Top"
- MouseLeftButtonDown="MyPresenter_MouseLeftButtonDown"
- LostMouseCapture="MyPresenter_LostMouseCapture"
- MouseMove="MyPresenter_MouseMove"
- Background="Transparent"
- Opacity="1" Width="480" Height="750" />
- </Grid>
- 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 Microsoft.Phone.Controls;
- // 引入以下命名空間。
- using System.Windows.Ink;
- namespace InkPresentSample
- {
- public partial class MainPage : PhoneApplicationPage
- {
- Stroke CurrentStroke = null;
- // 構(gòu)造函數(shù)
- public MainPage()
- {
- InitializeComponent();
- // 設(shè)置剪輯,以便收集墨跡
- RectangleGeometry rg = new RectangleGeometry();
- // 為了使范圍準(zhǔn)確,應(yīng)使用控件的最終呈現(xiàn)高度。
- rg.Rect = new Rect(0, 0, MyPresenter.ActualWidth, MyPresenter.ActualHeight);
- MyPresenter.Clip = rg;
- }
- private void MyPresenter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- // 當(dāng)我們點(diǎn)擊時(shí)獲捉鼠標(biāo)光標(biāo)
- MyPresenter.CaptureMouse();
- // 收集當(dāng)前的光標(biāo)所在的位置的點(diǎn)
- StylusPointCollection sc = new StylusPointCollection();
- sc.Add(e.StylusDevice.GetStylusPoints(MyPresenter));
- CurrentStroke = new Stroke(sc);
- // 設(shè)置筆觸的顏色,大小
- CurrentStroke.DrawingAttributes.Color = Colors.Yellow;
- CurrentStroke.DrawingAttributes.Width = 8;
- CurrentStroke.DrawingAttributes.Height = 8;
- // 把新的筆觸添加到集合中
- MyPresenter.Strokes.Add(CurrentStroke);
- }
- private void MyPresenter_LostMouseCapture(object sender, MouseEventArgs e)
- {
- // 當(dāng)釋放鼠標(biāo)時(shí),也同時(shí)釋放筆觸變量的引用
- CurrentStroke = null;
- }
- private void MyPresenter_MouseMove(object sender, MouseEventArgs e)
- {
- if (CurrentStroke != null)
- {
- // 每移動(dòng)一次鼠標(biāo),都收集對(duì)應(yīng)的點(diǎn)。
- CurrentStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyPresenter));
- }
- }
- }
- }