Windows Phone開發(21):做一個簡單的繪圖板
作者:junwong
Windows Phone是微軟發布的一款手機操作系統,它將微軟旗下的Xbox Live游戲、Xbox Music音樂與獨特的視頻體驗整合至手機中。
其實我們今天要說的就是一個控件——InkPresenter,這個控件并不是十分強大,沒辦法和WPF中的InkCanvas相比,估計在實際開發中也很少可能會用到它,不過,我們還是來了解一下吧,畢竟用起來也不難。
使用該控件沒有什么技術含量,注意一下以下幾點就是了:
1、必須明確指定InkPresenter的寬度和高度,也就是不能使用自動值和Margin,不然不能收集墨跡,除非里面有子元素;
2、要收集墨跡,要設置Clip屬性;
3、可以使用DrawingAttributes類設置墨跡的大小和顏色。
該控件不能像WPF那樣自動實現收集墨跡的功能,也就是說只能是我們自己寫代碼了。
- <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;
- // 構造函數
- public MainPage()
- {
- InitializeComponent();
- // 設置剪輯,以便收集墨跡
- RectangleGeometry rg = new RectangleGeometry();
- // 為了使范圍準確,應使用控件的最終呈現高度。
- rg.Rect = new Rect(0, 0, MyPresenter.ActualWidth, MyPresenter.ActualHeight);
- MyPresenter.Clip = rg;
- }
- private void MyPresenter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- // 當我們點擊時獲捉鼠標光標
- MyPresenter.CaptureMouse();
- // 收集當前的光標所在的位置的點
- StylusPointCollection sc = new StylusPointCollection();
- sc.Add(e.StylusDevice.GetStylusPoints(MyPresenter));
- CurrentStroke = new Stroke(sc);
- // 設置筆觸的顏色,大小
- 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)
- {
- // 當釋放鼠標時,也同時釋放筆觸變量的引用
- CurrentStroke = null;
- }
- private void MyPresenter_MouseMove(object sender, MouseEventArgs e)
- {
- if (CurrentStroke != null)
- {
- // 每移動一次鼠標,都收集對應的點。
- CurrentStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyPresenter));
- }
- }
- }
- }
責任編輯:閆佳明
來源:
oschina