Esta página está en construcción: perdonen los errores y temas inacabados.
 
This page is being developed: I am sorry for errors and unfinished subjects.

Cómo: Crear objetos Graphics para dibujar

De todo lo que viene después, ésta el la manera que henos comprobado en nuestro proyecto danzante, obtenido de Kinect Toolkit (Skeleton Basics) Cuidado. no todo es necesario, sólo sabemos que funciona):

__________________________________________________________________________________

Imports System.Windows.Forms
Imports System.Windows
Imports System.IO
Imports Microsoft.Kinect
Imports Microsoft.VisualBasic
'Imports System.Drawing
Imports System.Object
'‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒
' <copyright file="MainWindow.xaml.cs" company="Microsoft">
'‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒
Namespace Microsoft.Samples.Kinect.SkeletonBasics
 
Partial Public Class MainWindow
Inherits Window
Public margen As System.Windows.Thickness
''' Width of output drawing
Private Const RenderWidth As Single = 640.0F
''' Height of our output drawing
Private Const RenderHeight As Single = 480.0F
''' Thickness of drawn joint lines
Private Const JointThickness As Double = 3
''' Thickness of body center ellipse
Private Const BodyCenterThickness As Double = 20 '''10
''' Thickness of clip edge rectangles
Private Const ClipBoundsThickness As Double = 10
''' Brush used to draw skeleton center point
Private ReadOnly centerPointBrush As Brush = Brushes.Blue
''' Brush used for drawing joints that are currently tracked
Private ReadOnly trackedJointBrush As Brush = New SolidColorBrush(Color.FromArgb(255, 68, 192, 68))
''' Brush used for drawing joints that are currently inferred
Private ReadOnly inferredJointBrush As Brush = Brushes.Yellow
''' Pens used for drawing bones that are currently tracked
Private ReadOnly trackedBonePen As New Pen(Brushes.Green, 6)
Private ReadOnly manos As New Pen(Brushes.BlueViolet, 20)
Private ReadOnly ManoDerecha As New Pen(Brushes.CadetBlue, 20)
Private ReadOnly ManoIzquierda As New Pen(Brushes.Blue, 20)
''' Pen used for drawing bones that are currently inferred
Private ReadOnly inferredBonePen As New Pen(Brushes.Gray, 1)
''' Active Kinect sensor
''' Drawing group for skeleton rendering output
Private drawingGroup As DrawingGroup
''' Drawing image that we will display
Private imageSource As DrawingImage
''' Initializes a new instance of the MainWindow class.
Public Sub New()
InitializeComponent()
End Sub
''' Execute startup tasks
''' <param name="sender">object sending the event</param>
''' <param name="e">event arguments</param>
Private Sub WindowLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Create the drawing group we'll use for drawing
Me.drawingGroup = New DrawingGroup()
' Create an image source that we can use in our image control
Me.imageSource = New DrawingImage(Me.drawingGroup)
' Display the drawing using our image control
Image.Source = Me.imageSource
' Look through all sensors and start the first connected one.
' This requires that a Kinect is connected at the time of app startup.
' To make your app robust against plug/unplug, it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit (See components in Toolkit Browser).
For Each sensorItem In KinectSensor.KinectSensors
If sensorItem.Status = KinectStatus.Connected Then
Me.sensor = sensorItem
''' Event handler for Kinect sensor's SkeletonFrameReady event
'Return
Using dc As DrawingContext = Me.drawingGroup.Open()
' Draw a transparent background to set the render size
dc.DrawRectangle(Brushes.Black, Nothing, New Rect(0.0, 0.0, RenderWidth, RenderHeight))
If skeletons.Length <> 0 Then
For Each skel As Skeleton In skeletons
Me.RenderClippedEdges(skel, dc)
If skel.TrackingState = SkeletonTrackingState.Tracked Then
Me.DrawBonesAndJoints(skel, dc)
ElseIf skel.TrackingState = SkeletonTrackingState.PositionOnly Then
dc.DrawEllipse(Me.centerPointBrush, Nothing, Me.SkeletonPointToScreen(skel.Position), BodyCenterThickness, BodyCenterThickness)
End If
Next skel
End If
End Using
End Sub
''' Draws indicators to show which edges are clipping skeleton data
''' <param name="skeleton">skeleton to draw clipping information for</param>
''' <param name="drawingContext">drawing context to draw to</param>
Private Sub RenderClippedEdges(ByVal skeleton As Skeleton, ByVal drawingContext As DrawingContext)
If skeleton.ClippedEdges.HasFlag(FrameEdges.Bottom) Then
drawingContext.DrawRectangle(Brushes.Red, Nothing, New Rect(0, RenderHeight - ClipBoundsThickness, RenderWidth, ClipBoundsThickness))
End If
If skeleton.ClippedEdges.HasFlag(FrameEdges.Top) Then
drawingContext.DrawRectangle(Brushes.Red, Nothing, New Rect(0, 0, RenderWidth, ClipBoundsThickness))
End If
If skeleton.ClippedEdges.HasFlag(FrameEdges.Left) Then
drawingContext.DrawRectangle(Brushes.Red, Nothing, New Rect(0, 0, ClipBoundsThickness, RenderHeight))
End If
If skeleton.ClippedEdges.HasFlag(FrameEdges.Right) Then
drawingContext.DrawRectangle(Brushes.Red, Nothing, New Rect(RenderWidth - ClipBoundsThickness, 0, ClipBoundsThickness, RenderHeight))
End If
End Sub
'SUPRIMO TODO MENOS MUÑECAS (Y algunas articulaciones)
''' Draws a skeleton's bones and joints
''' <param name="skeleton">skeleton to draw</param>
''' <param name="drawingContext">drawing context to draw to</param>
Private Sub DrawBonesAndJoints(ByVal skeleton As Skeleton, ByVal drawingContext As DrawingContext)
' Render Torso
Me.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft)
Me.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight)
 
' Render Joints
Dim drawBrush As Brush = Nothing
drawBrush = Me.trackedJointBrush
drawBrush = Me.inferredJointBrush
 
If drawBrush IsNot Nothing Then
drawingContext.DrawEllipse(drawBrush, Nothing, Me.SkeletonPointToScreen(joint.Position), JointThickness, JointThickness)
End Sub
''' Clips a SkeletonPoint to lie within our output space and converts to Point
''' <param name="skelpoint">point to convert and clip</param>
''' <returns>converted and clipped point</returns>
Private Function SkeletonPointToScreen(ByVal skelpoint As SkeletonPoint) As Point
' Convert point to depth space.
' We are not using depth directly, but we do want the points in our 640x480 output resolution.
Dim depthPoint As DepthImagePoint = Me.sensor.CoordinateMapper.MapSkeletonPointToDepthPoint(skelpoint, DepthImageFormat.Resolution640x480Fps30)
' Restrict to our render space
Dim x As Double = depthPoint.X
If x > RenderWidth Then
x = RenderWidth
ElseIf x < 0 Then
x = 0
End If
Dim y As Double = depthPoint.Y
If y > RenderHeight Then
y = RenderHeight
ElseIf y < 0 Then
y = 0
End If
Return New Point(x, y)
End Function
 
''' Draws a bone line between two joints
''' <param name="jointType1">joint to end drawing at</param>
Private Sub DrawBone(ByVal skeleton As Skeleton, ByVal drawingContext As DrawingContext, ByVal jointType0 As JointType,
ByVal jointType1 As JointType)
Dim joint0 As Joint = skeleton.Joints(jointType0)
Dim joint1 As Joint = skeleton.Joints(jointType1)
' If we can't find either of these joints, exit
' We assume all drawn bones are inferred unless BOTH joints are tracked
Dim drawPen As Pen = Me.inferredBonePen
drawPen = Me.trackedBonePen
drawPen = Me.ManoIzquierda
drawPen = Me.ManoDerecha
 drawingContext.DrawEllipse(Brushes.BlanchedAlmond, drawPen, Me.SkeletonPointToScreen(joint0.Position), 10, 20)
 drawingContext.DrawLine(drawPen, Me.SkeletonPointToScreen(joint0.Position), Me.SkeletonPointToScreen(joint1.Position))
 

__________________________________________________________________________________

 

Información varia:

 

.NET Framework 3.5

Actualización: noviembre 2007
Antes de dibujar líneas y formas, representar texto o mostrar y manipular imágenes con GDI+ es preciso crear un objeto Graphics. El objeto Graphics representa una superficie de dibujo de GDI+ y es el objeto que se usa para crear imágenes gráficas.

Para trabajar con gráficos existen los dos pasos siguientes:

  1. Crear un objeto Graphics.
  2. Usar el objeto Graphics para dibujar líneas y formas, representar texto o mostrar y manipular imágenes.
El objeto Graphics se puede crear de diversas formas.

Para crear un objeto Graphics

  • Reciba una referencia a un objeto Graphics como parte de PaintEventArgs del evento Paint de un formulario o un control. Este es el modo en que normalmente se obtiene una referencia a un objeto Graphics cuando se crea código de dibujo para un control.

    O bien

  • Llame al método CreateGraphics de un control o un formulario para obtener una referencia a un objeto Graphics que represente la superficie de dibujo de dicho control o formulario. Utilice este método si desea dibujar en un formulario o en un control que ya existía con anterioridad.

    O bien

  • Cree un objeto Graphics a partir de cualquier objeto que herede de Image. Este método resulta útil cuando se desea alterar una imagen que ya existe.

    Las secciones siguientes proporcionan detalles sobre cada uno de estos procesos.

Al programar PaintEventHandler para los controles, se proporciona un objeto gráfico como uno de los PaintEventArgs.

Para obtener una referencia a un objeto Graphics a partir de PaintEventArgs en el evento Paint

  1. Declare el objeto Graphics.
  2. Asigne la variable que hará referencia al objeto Graphics pasado como parte de PaintEventArgs.
  3. Inserte código para dibujar en el formulario o control.

En el ejemplo siguiente se muestra cómo hacer referencia a un objeto Graphics desde PaintEventArgs en el evento Paint:

Private Sub Form1_Paint(sender As Object, pe As PaintEventArgs) Handles _
   MyBase.Paint
   ' Declares the Graphics object and sets it to the Graphics object
   ' supplied in the PaintEventArgs.
   Dim g As Graphics = pe.Graphics
   ' Insert code to paint the form here.
End Sub

CreateGraphics (Método)


También puede utilizar el método CreateGraphics de un control o un formulario para obtener una referencia a un objeto Graphics que represente la superficie de dibujo de dicho control o formulario.

Para crear un objeto Graphics con el método CreateGraphics

  • Llame al método CreateGraphics del formulario o del control en el que desee representar gráficos.
    Dim g as Graphics
    ' Sets g to a Graphics object representing the drawing surface of the
    ' control or form g is a member of.
    g = Me.CreateGraphics
    
    Copiar
    Graphics g;
    // Sets g to a graphics object representing the drawing surface of the
    // control or form g is a member of.
    g = this.CreateGraphics();
    

    C++

    Graphics ^ g;
    // Sets g to a graphics object representing the drawing surface of the
    // control or form g is a member of.
    g = this->CreateGraphics();
    
También se puede crear un objeto Graphics a partir de cualquier objeto que se derive de la clase Image.

Para crear un objeto Graphics a partir de un objeto Image

  • Llame al método Graphics.FromImage, suministrando el nombre de la variable Image a partir de la cual desea crear un objeto Graphics.

En el ejemplo siguiente se muestra cómo usar un objeto Bitmap:

Dim myBitmap as New Bitmap("C:\Documents and Settings\Joe\Pics\myPic.bmp")
Dim g as Graphics = Graphics.FromImage(myBitmap)
Nota:
Sólo puede crear objetos Graphics a partir de archivos .bmp no indizados, como archivos .bmp de 16 bits, 24 bits y 32 bits. Cada píxel de archivos .bmp no indizados alberga un color, a diferencia de los píxeles de los archivos .bmp indizados, que albergan un índice que hace referencia a una tabla de colores.
Una vez creado el objeto Graphics, éste se puede usar para dibujar líneas y formas, representar texto o mostrar y manipular imágenes. Los objetos principales que se usan con el objeto Graphics son:
  • La clase Pen: se utiliza para dibujar líneas y contornos de formas o para representar otros elementos geométricos.
  • La clase Brush: se utiliza para rellenar áreas de gráficos, como formas rellenas, imágenes o texto.
  • La clase Font: proporciona una descripción de las formas que se utilizarán al representar texto.
  • La estructura Color: representa los distintos colores para mostrar.

Para utilizar el objeto Graphics que ha creado

Espacio de nombres:  System.Drawing
Ensamblado:  System.Drawing (en System.Drawing.dll)

Sintaxis

'Declaración
Public NotInheritable Class Graphics _
	Inherits MarshalByRefObject _
	Implements IDeviceContext, IDisposable
'Uso
Dim instance As Graphics
public final class Graphics extends MarshalByRefObject implements IDeviceContext, 
	IDisposable
public final class Graphics 
 

Vuelta al Principio    Última actualización: viernes, 13 de mayo de 2016    Visitantes: contador de visitas