2011-11-11 9 views
7

Simplemente quiero que el usuario pueda dibujar en la pantalla con algún tipo de puntero.¿Cómo dibujar en la pantalla para Windows Metro Style Apps en C#?

Ya tengo el código en funcionamiento que captura la posición del puntero, pero no puedo encontrar la forma de colocar los píxeles o las formas o lo que sea en la pantalla.

He encontrado útil este tutorial:
http://www.dotnetspeaks.com/DisplayArticle.aspx?ID=137

Y yo he estado mirando la documentación aquí:
http://msdn.microsoft.com/en-us/library/windows/apps/hh465055(v=VS.85).aspx

No hubo suerte hasta ahora. = (El tutorial es para Windows Phone 7, por lo que es un poco diferente. = \ Ayuda, por favor? =)

Y esto es lo que tengo hasta ahora.

La parte dibujo:

private void Image_PointerPressed(object sender, PointerEventArgs e) 
    { 
     Debug.WriteLine("Image_PointerPressed"); 
     isTracing = true; 
    } 

    private void Image_PointerReleased(object sender, PointerEventArgs e) 
    { 
     Debug.WriteLine("Image_PointerReleased"); 
     isTracing = false; 
    } 

    private void Image_PointerMoved(object sender, PointerEventArgs e) 
    { 
     Debug.WriteLine("Image_PointerMoved"); 
     Debug.WriteLine(e.GetCurrentPoint(this).Position); 
     if (isTracing) 
     { 
      Debug.WriteLine("isTracing"); 

      Point pos = e.GetCurrentPoint(this).Position; 
      Color color = Colors.Green; 
      Line line = new Line() { X1 = pos.X, X2 = pos.X + 1, Y1 = pos.Y, Y2 = pos.Y + 1 }; 
      line.Stroke = new SolidColorBrush(color); 
      line.StrokeThickness = 15; 
      //// So how do I draw this line onto the screen?? //// 

     } 

    } 

Como referencia, las cosas en otra parte del código:

 

    using System; 
    using System.Collections.Generic; 
    using System.Diagnostics; 
    using System.IO; 
    using System.Linq; 
    using System.Threading.Tasks; 
    using Multimedia.FFmpeg; 
    using Windows.Foundation; 
    using Windows.Storage; 
    using Windows.Storage.Pickers; 
    using Windows.Storage.Streams; 
    using Windows.UI.Xaml; 
    using Windows.UI.Xaml.Controls; 
    using Windows.UI.Xaml.Shapes; 
    using Windows.UI.Xaml.Media; 
    using Windows.UI.Xaml.Input; 
    using Windows.UI.Input; 

    bool isTracing = false; 

+0

También encontré este tutorial, pero todavía no ayudó. http://www.windowsphonegeek.com/tips/drawing-in-wp7-1-getting-started-and-line-shape – Crystal

+0

¿Qué no funciona bien con el código que ya tiene? –

+0

No estoy dibujando nada en la pantalla. No sé qué usar para hacer eso. (Por cierto, ¡gracias por comentar!) – Crystal

Respuesta

6

breve formulario:

  • Añadir Line s y Rectangle s de un panel
  • manipular un mapa de bits directamente
  • uso un elemento Canvas de HTML5 en un proyecto de JavaScript/HTML
  • escribir todo lo en C++/DirectX

Metro/XAML no tiene forma de sobreescribir un OnRender() método o similar. Sus opciones son agregar elementos gráficos existentes (por ejemplo, desde el Shapes namespace) a un lienzo u otro panel, o manipular directamente los píxeles en un mapa de bits y empujar ese mapa de bits en un elemento de imagen.

Metro/C# solo tiene un dibujo de gráficos de modo retenido, lo que significa que lo único que representará son objetos que se han agregado a la jerarquía de vistas. Lo que estamos buscando es una especie de modo inmediato de dibujo de gráficos, por ejemplo

myCanvas.DrawLine(fromPoint, toPoint); 

Esto se puede hacer en un proyecto/HTML JavaScript usando HTML5's Canvas object. Lo cual, lamentablemente, es la forma en que me inclino a tal proyecto. Es desafortunado que Microsoft no proporcione un elemento de modo inmediato para los proyectos XAML, pero así son las cosas. C++/DirectX también es una opción para hacer dibujos personalizados, pero requiere una revisión sustancial de todo lo demás que está haciendo en la aplicación.

0

se debe añadir la línea a un elemento de interfaz de usuario, como un lienzo.

0

El principal problema en su código es que no se está adjuntando, la línea a cualquier elemento XAML le sugiero que lo haga a un elemento Canvas, más o menos así:

newCanvas.Children.Add(line); 

Una alternativa es usar Modern Components Drawing Library, funciona en WinRT, usa clases de gráficos .NET como llamadas y dibuja directamente en un lienzo XAML, tenga en cuenta que si desea guardar la imagen como un mapa de bits, es posible que necesite utilizar también WritableBitmapEx, ya que XAML Canvas no se puede representar en Bitmaps.

0

Este proyecto muestra tiene código para dibujar en la pantalla para Win 8 tienda de aplicaciones en C#/XAML:

http://code.msdn.microsoft.com/windowsapps/Drawing-on-a-Canvas-with-33510ae6

Aquí está el archivo C# relevante:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using Windows.Devices.Input; 
using Windows.Foundation; 
using Windows.Foundation.Collections; 
using Windows.UI; 
using Windows.UI.Input; 
using Windows.UI.Input.Inking; //we need to add this name space in order to have many functions 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 
using Windows.UI.Xaml.Shapes; 
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 

namespace DrawingOnCanvasWithInkPen 
{ 
/// <summary> 
/// An empty page that can be used on its own or navigated to within a Frame. 
/// </summary> 
public sealed partial class MainPage : Page 
{ 
    InkManager _inkKhaled = new Windows.UI.Input.Inking.InkManager(); 
    private uint _penID; 
    private uint _touchID; 
    private Point _previousContactPt; 
    private Point currentContactPt; 
    private double x1; 
    private double y1; 
    private double x2; 
    private double y2; 


    public MainPage() 
    { 
     this.InitializeComponent(); 

     MyCanvas.PointerPressed += new PointerEventHandler(MyCanvas_PointerPressed); 
     MyCanvas.PointerMoved += new PointerEventHandler(MyCanvas_PointerMoved); 
     MyCanvas.PointerReleased += new PointerEventHandler(MyCanvas_PointerReleased); 
     MyCanvas.PointerExited += new PointerEventHandler(MyCanvas_PointerReleased); 
    } 


    #region PointerEvents 
    private void MyCanvas_PointerReleased(object sender, PointerRoutedEventArgs e) 
    { 
     if (e.Pointer.PointerId == _penID) 
     { 
      Windows.UI.Input.PointerPoint pt = e.GetCurrentPoint(MyCanvas); 

      // Pass the pointer information to the InkManager. 
      _inkKhaled.ProcessPointerUp(pt); 
     } 

     else if (e.Pointer.PointerId == _touchID) 
     { 
      // Process touch input 
     } 

     _touchID = 0; 
     _penID = 0; 

     // Call an application-defined function to render the ink strokes. 


     e.Handled = true; 
    } 

    private void MyCanvas_PointerMoved(object sender, PointerRoutedEventArgs e) 
    { 
     if (e.Pointer.PointerId == _penID) 
     { 
      PointerPoint pt = e.GetCurrentPoint(MyCanvas); 

      // Render a red line on the canvas as the pointer moves. 
      // Distance() is an application-defined function that tests 
      // whether the pointer has moved far enough to justify 
      // drawing a new line. 
      currentContactPt = pt.Position; 
      x1 = _previousContactPt.X; 
      y1 = _previousContactPt.Y; 
      x2 = currentContactPt.X; 
      y2 = currentContactPt.Y; 

      if (Distance(x1, y1, x2, y2) > 2.0) // We need to developp this method now 
      { 
       Line line = new Line() 
       { 
        X1 = x1, 
        Y1 = y1, 
        X2 = x2, 
        Y2 = y2, 
        StrokeThickness = 4.0, 
        Stroke = new SolidColorBrush(Colors.Green) 
       }; 

       _previousContactPt = currentContactPt; 

       // Draw the line on the canvas by adding the Line object as 
       // a child of the Canvas object. 
       MyCanvas.Children.Add(line); 

       // Pass the pointer information to the InkManager. 
       _inkKhaled.ProcessPointerUpdate(pt); 
      } 
     } 

     else if (e.Pointer.PointerId == _touchID) 
     { 
      // Process touch input 
     } 

    } 

    private double Distance(double x1, double y1, double x2, double y2) 
    { 
     double d = 0; 
     d = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); 
     return d; 
    } 

    private void MyCanvas_PointerPressed(object sender, PointerRoutedEventArgs e) 
    { 
     // Get information about the pointer location. 
     PointerPoint pt = e.GetCurrentPoint(MyCanvas); 
     _previousContactPt = pt.Position; 

     // Accept input only from a pen or mouse with the left button pressed. 
     PointerDeviceType pointerDevType = e.Pointer.PointerDeviceType; 
     if (pointerDevType == PointerDeviceType.Pen || 
       pointerDevType == PointerDeviceType.Mouse && 
       pt.Properties.IsLeftButtonPressed) 
     { 
      // Pass the pointer information to the InkManager. 
      _inkKhaled.ProcessPointerDown(pt); 
      _penID = pt.PointerId; 

      e.Handled = true; 
     } 

     else if (pointerDevType == PointerDeviceType.Touch) 
     { 
      // Process touch input 
     } 
    } 

    #endregion 

    /// <summary> 
    /// Invoked when this page is about to be displayed in a Frame. 
    /// </summary> 
    /// <param name="e">Event data that describes how this page was reached. The Parameter 
    /// property is typically used to configure the page.</param> 
    protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
    } 
} 

}

y archivo xaml:

<Page 

x:Class="DrawingOnCanvasWithInkPen.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:DrawingOnCanvasWithInkPen" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"> 

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
    <Canvas Name="MyCanvas" Background="White" HorizontalAlignment="Left" Height="513" Margin="83,102,0,0" VerticalAlignment="Top" Width="1056"/> 

</Grid> 

En su estado actual, sólo los procesos de entrada de lápiz o el ratón - pero yo también tengo que trabajar para el tacto con ligeras modificaciones.

Cuestiones relacionadas