Está en la página 1de 70

Textos Universitarios / Serie Docencia

________________________________________________________________________
135
Captulo 4
Pinceles y Plumas

En el captulo anterior vimos que para dibujar una figura, ya sea lnea, rectngulo o
trazo, es necesario el uso de una pluma (pen) y que para poder rellenar el interior de ellas
era necesario el uso de un pincel (brush). En este captulo estudiaremos en detalle como
crear y usar varios tipos de pinceles y plumas.

4.1 Uso de pinceles en GDI+

En la biblioteca del Framework.NET hay dos espacios de nombres donde encontramos
definida la funcionalidad para trabajar con pinceles: el espacio de nombres
System.Drawing que define clases y funcionalidad de pinceles genricos y el espacio de
nombres System.Drawing.Drawing2D que define funcionalidad avanzada en 2D para
los pinceles. En el espacio de nombres System.Drawing encontramos las clases Brush,
SolidBrush, TextureBrush y Brushes y en el espacio de nombres
System.Drawing.Drawing2D encontramos las clases HatchBrush, GradientBrush y
PathGradientBrush que son mas elaboradas.

4.1.1 Clase Brush
15

Requisitos

Espacio de nombres: System.Drawing.Brush

Las clases derivadas de esta clase base abstracta definen objetos utilizados para rellenar
el interior de formas grficas, como rectngulos, elipses, grficos circulares, polgonos y
rutas o trazos.



Figura 4.1. Clases heredadas de la clase Brush

15
http://msdn2.microsoft.com/en-us/library/system.drawing.brush(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
136
4.1.1.1 Mtodos pblicos
Clone Cuando se anula en una clase derivada, crea
una copia exacta de este objeto Brush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose . Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
4.1.1.2 Mtodos protegidos
Finalize Reemplazado. Vea Object.Finalize.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.

4.1.2 Clase SolidBrush
16

Requisitos

Espacio de nombres: System.Drawing.SolidBrush

Define un pincel de un solo color. Los pinceles se utilizan para rellenar formas de
grficos, por ejemplo rectngulos, elipses, grficos circulares y rutas o trazos. No se
puede heredar esta clase.

16
http://msdn2.microsoft.com/en-us/library/system.drawing.solidbrush(VS.80).aspx
Junio 3 de 2006
Textos Universitarios / Serie Docencia
________________________________________________________________________
137
4.1.2.1 Constructores pblicos
SolidBrush (Constructor) Inicializa un nuevo objeto SolidBrush del
color especificado.
4.1.2.2 Propiedades pblicas
Color Obtiene o establece el color de este objeto
SolidBrush.
4.1.2.3 Mtodos pblicos
Clone Reemplazado. Crea una copia exacta de este
objeto SolidBrush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose (se hereda de Brush) Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
4.1.2.4 Mtodos protegidos
Finalize (se hereda de Object) Reemplazado. Permite que un objeto Object
intente liberar recursos y realizar otras
operaciones de limpieza antes de que el
objeto Object sea reclamado por el
recolector de elementos no utilizados.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
Jenaro C. Paz
________________________________________________________________________
138
actual.


4.1.2.5 El uso de SolidBrush en una forma Web

Los listados 18b, 19b, 20b, 21b, 22b y 23b son ejemplos del uso de SolidBrush para
rellenar diferente tipo de formas. Solo para resumir incluimos el siguiente segmento de
cdigo en donde se crea una pincel redBrush de color slido y se rellena el interior de un
rectngulo haciendo uso de el.


SolidBrush redBrush = new SolidBrush(Color.Red);
Rectangle rect = new Rectangle(150, 80, 200, 140);
g.FillRectangle(redBrush, rect);
redBrush.Dispose();



4.1.3 Clase TextureBrush
17

Requisitos

Espacio de nombres: System.Drawing.TextureBrush
Cada una de las propiedades de la clase TextureBrush es un objeto Brush que utiliza una
imagen para rellenar el interior de una forma. No se puede heredar esta clase.
4.1.3.1 Constructores pblicos
TextureBrush (Constructor) Sobrecargado. Inicializa un nuevo objeto
TextureBrush que utiliza la imagen
especificada.
4.1.3.2 Propiedades pblicas
Image Obtiene el objeto Image asociado a este
objeto TextureBrush.
Transform Obtiene o establece un objeto Matrix que
define una transformacin geomtrica local
para la imagen asociada a este objeto
TextureBrush.
WrapMode Obtiene o establece una enumeracin
WrapMode que indica el modo de ajuste de
este objeto TextureBrush.

17
http://msdn2.microsoft.com/en-us/library/system.drawing.texturebrush(VS.80).aspx
Junio 3 de 2006
Textos Universitarios / Serie Docencia
________________________________________________________________________
139
4.1.3.3 Mtodos pblicos
Clone Reemplazado. Crea una copia exacta de este
objeto TextureBrush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose (se hereda de Brush) Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
MultiplyTransform Sobrecargado. Multiplica el objeto Matrix
que representa la transformacin geomtrica
local de este objeto TextureBrush por el
objeto Matrix especificado, en el orden
indicado.
ResetTransform Restablece la propiedad Transform de este
objeto TextureBrush en identidad.
RotateTransform Sobrecargado. Gira la transformacin
geomtrica local de este objeto
TextureBrush en la cantidad especificada.
Este mtodo antepone la rotacin a la
transformacin.
ScaleTransform Sobrecargado. Cambia el tamao de la
transformacin geomtrica local de este
objeto TextureBrush en la cantidad
especificada. Este mtodo antepone la
matriz de escala a la transformacin.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
TranslateTransform Sobrecargado. Desplaza la transformacin
geomtrica local de este objeto
Jenaro C. Paz
________________________________________________________________________
140
TextureBrush en las dimensiones y en el
orden especificados.
4.1.3.4 Mtodos protegidos
Finalize (se hereda de Object) Reemplazado. Permite que un objeto Object
intente liberar recursos y realizar otras
operaciones de limpieza antes de que el
objeto Object sea reclamado por el
recolector de elementos no utilizados.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.



4.1.3.5 El uso de TextureBrush en una forma Web

Forma PaintBrushes01.aspx


Figura 4.2. Forma Web para trabajar con Pinceles

PaintBrushes01.aspx.cs

using System;
Textos Universitarios / Serie Docencia
________________________________________________________________________
141
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace JCPGraphics
{
/// <summary>
/// Descripcin breve de DibujaCuadro.
/// </summary>
public class PaintBrushes01 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtWidth;
protected System.Web.UI.WebControls.Button btnBuild;
protected System.Web.UI.WebControls.DropDownList ColorList;
protected System.Web.UI.WebControls.TextBox txtHeight;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.btnBuild.Click += new
System.EventHandler(this.btnBuild_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintBrushes01.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "&valueC=" + theColor + "'>"+
"</p>");
}
}
Jenaro C. Paz
________________________________________________________________________
142
}

ServerPaintBrushes01.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{


public class ServerPaintBrushes01 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// +++++++++++++++Begins section related with this Server
Textos Universitarios / Serie Docencia
________________________________________________________________________
143
//
Bitmap bitmap = new Bitmap(Server.MapPath("Textura.png"));
TextureBrush tbrush = new TextureBrush(bitmap);
g.FillRectangle(tbrush,bgRect);
g.FillRectangle(new SolidBrush(Color.FromArgb(180, bgColor)),
bgRect);
Pen colorPen = new Pen(bgColor,8);
g.DrawRectangle(colorPen,bgRect);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code
}
}



Figura 4.3. Pintando un lienzo con Pinceles de Textura y Slidos


4.1.4 Clase HatchBrush
18

Requisitos

Espacio de nombres: System.Drawing.Drawing2D.HatchBrush

18
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.hatchbrush(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
144
Define un pincel rectangular con un estilo de trama, un color de primer plano y un color
de fondo. No se puede heredar esta clase.
4.1.4.1 Constructores pblicos
HatchBrush (Constructor) Sobrecargado. Inicializa una nueva instancia
de la clase HatchBrush con la enumeracin
HatchStyle y el color de primer plano
especificados.
4.1.4.2 Propiedades pblicas
BackgroundColor Obtiene el color de los espacios entre las
lneas de trama dibujadas por este objeto
HatchBrush.
ForegroundColor Obtiene el color de las lneas de trama
dibujadas por este objeto HatchBrush.
HatchStyle Obtiene el estilo de trama de este objeto
HatchBrush.
4.1.4 3 Mtodos pblicos
Clone Reemplazado. Crea una copia exacta de este
objeto HatchBrush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose (se hereda de Brush) Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
Textos Universitarios / Serie Docencia
________________________________________________________________________
145
4.1.4 4 Mtodos protegidos
Finalize (se hereda de Object) Reemplazado. Permite que un objeto Object
intente liberar recursos y realizar otras
operaciones de limpieza antes de que el
objeto Object sea reclamado por el
recolector de elementos no utilizados.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.

4.1.4.5 El uso de HatchBrush en una forma Web

PaintBrushes02.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintBrushes02.aspx?valueH=" +
recHeight + "&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}

ServerPaintBrushes02.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{


public class ServerPaintBrushes02 : System.Web.UI.Page
Jenaro C. Paz
________________________________________________________________________
146
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
HatchBrush hbrush = new HatchBrush(HatchStyle.DiagonalBrick,
Color.Green, Color.FromArgb(200, Color.Yellow));
g.FillEllipse(hbrush,bgRect.X+10,bgRect.Y+10,
bgRect.Width-20,bgRect.Height-20);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}

Estilos para pinceles HatchBrush
BackwardDiagonal Cross DarkDownwardDiagonal DarkHorizontal DarkUpwardDiagonal
DarkVertical DashedDownwardDiagonal DashedHorizontal DashedUpwardDiagonal DashedVertical
DiagonalBrick DiagonalCross Divot DottedDiamond DottedGrid
ForwardDiagonal Horizontal HorizontalBrick LargeCheckerBoard LargeConfetti
LargeGrid LightDownwardDiagonal LightHorizontal LightUpwardDiagonal LightVertical
Max Min NarrowHorizontal NarrowVertical OutlinedDiamond
Percent05 Percent10 Percent20 Percent25 Percent30
Textos Universitarios / Serie Docencia
________________________________________________________________________
147
Percent40 Percent50 Percent60 Percent70 Percent75
Percent80 Percent90 Plaid Shingle SmallCheckerBoard
SmallConfetti SmallGrid SolidDiamond Sphere Trellis
Vertical Wave Weave WideDownwardDiagonal WideUpwardDiagonal
ZigZag



Figura 4.4. Pinceles HatchBrush con estilos ForwardDiagonal, DiagonalBrick y Wave


4.1.5 Clase LinearGradientBrush
19

Requisitos

Espacio de nombres: System.Drawing.Drawing2D.LinearGradientBrush
Encapsula un objeto Brush con un degradado lineal. No se puede heredar esta clase.
4.1.5.1 Constructores pblicos
LinearGradientBrush (Constructor) Sobrecargado. Inicializa una nueva instancia
de la clase LinearGradientBrush con los
puntos y colores especificados.

19
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.lineargradientbrush(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
148
4.1.5.2 Propiedades pblicas
Blend Obtiene o establece un objeto Blend que
especifica las posiciones y factores que
definen una disminucin personalizada para
el degradado.
GammaCorrection Obtiene o establece un valor que indica si se
habilit la correccin gamma para este
objeto LinearGradientBrush.
InterpolationColors Obtiene o establece un objeto ColorBlend
que define un degradado lineal de varios
colores.
LinearColors Obtiene o establece los colores inicial y
final del degradado.
Rectangle Obtiene un rea rectangular que define los
puntos inicial y final del degradado.
Transform Obtiene o establece un objeto Matrix que
define una transformacin geomtrica local
para este objeto LinearGradientBrush.
WrapMode Obtiene o establece una enumeracin
WrapMode que indica el modo de ajuste de
este LinearGradientBrush.
4.1.5.3 Mtodos pblicos
Clone Reemplazado. Crea una copia exacta de este
objeto LinearGradientBrush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose (se hereda de Brush) Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
Textos Universitarios / Serie Docencia
________________________________________________________________________
149
esta instancia.
MultiplyTransform Sobrecargado. Multiplica el objeto Matrix
que representa la trasformacin geomtrica
local de este objeto LinearGradientBrush
por el objeto Matrix anteponindole el
objeto Matrix especificado.
ResetTransform Restablece la propiedad Transform en
identidad.
RotateTransform Sobrecargado. Gira la transformacin
geomtrica local la cantidad especificada.
Este mtodo antepone la rotacin a la
transformacin.
ScaleTransform Sobrecargado. Cambia el tamao de la
transformacin geomtrica local en las
cantidades especificadas. Este mtodo
antepone la matriz de escala a la
transformacin.
SetBlendTriangularShape Sobrecargado. Crea un degradado lineal con
un color central y una disminucin lineal
hacia un nico color en ambos extremos.
SetSigmaBellShape Sobrecargado. Crea una disminucin de
degradado basada en una curva en forma de
campana.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
TranslateTransform Sobrecargado. Convierte la transformacin
geomtrica local en las dimensiones
especificadas. Este mtodo antepone la
conversin a la transformacin.
4.1.5.4 Mtodos protegidos
Finalize (se hereda de Object) Reemplazado. Permite que un objeto Object
intente liberar recursos y realizar otras
operaciones de limpieza antes de que el
objeto Object sea reclamado por el
recolector de elementos no utilizados.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.


4.1.5.5 El uso de LinearGradientBrush en una forma Web
Jenaro C. Paz
________________________________________________________________________
150

PaintBrushes03.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintBrushes03.aspx?valueH=" +
recHeight + "&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}

ServerPaintBrushes03.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{


public class ServerPaintBrushes03 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
Textos Universitarios / Serie Docencia
________________________________________________________________________
151
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//

Rectangle rect = new Rectangle(bgRect.X+10,
bgRect.Y+10,bgRect.Width-20,bgRect.Height-20);

LinearGradientBrush lbrush = new LinearGradientBrush(rect,
Color.Blue, Color.Turquoise,
LinearGradientMode.ForwardDiagonal);
g.FillEllipse(lbrush,rect);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}

LinearGradientMode
BackwardDiagonal ForwardDiagonal Horizontal Vertical

Jenaro C. Paz
________________________________________________________________________
152

Figura 4.5. Pinceles LinearGradientBrush con estilos ForwardDiagonal, Horizontal y Vertical


4.1.6 Clase PathGradientBrush
20

Requisitos

Espacio de nombres: System.Drawing.Drawing2D.PathGradientBrush

Encapsula un objeto Brush que rellena el interior de un objeto GraphicsPath con un
degradado. No se puede heredar esta clase.
4.1.6.1 Constructores pblicos
PathGradientBrush (Constructor) Sobrecargado. Inicializa una nueva instancia
de la clase PathGradientBrush con el
trazado especificado.
4.1.6.2 Propiedades pblicas
Blend Obtiene o establece un objeto Blend que
especifica las posiciones y factores que
definen una disminucin personalizada para
el degradado.
CenterColor Obtiene o establece el color en el centro del
trazado del degradado.

20
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.pathgradientbrush(VS.80).aspx
Junio 3 ,de 2006
Textos Universitarios / Serie Docencia
________________________________________________________________________
153
CenterPoint Obtiene o establece el punto central del
trazado del degradado.
FocusScales Obtiene o establece el punto de foco para la
disminucin del degradado.
InterpolationColors Obtiene o establece un objeto ColorBlend
que define un degradado lineal de varios
colores.
Rectangle Obtiene un rectngulo delimitador para este
objeto PathGradientBrush.
SurroundColors Obtiene o establece una matriz de colores
que corresponde a los puntos del trazado
que rellena este objeto
PathGradientBrush.
Transform Obtiene o establece un objeto Matrix que
define una transformacin geomtrica local
para este objeto PathGradientBrush.
WrapMode Obtiene o establece una enumeracin
WrapMode que indica el modo de ajuste de
este objeto PathGradientBrush.
4.1.6.3 Mtodos pblicos
Clone Reemplazado. Crea una copia exacta de este
objeto PathGradientBrush.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose (se hereda de Brush) Sobrecargado.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
MultiplyTransform Sobrecargado. Multiplica el objeto Matrix
Jenaro C. Paz
________________________________________________________________________
154
que representa la trasformacin geomtrica
local de este objeto PathGradientBrush
por el objeto Matrix especificado,
anteponindole el objeto Matrix
especificado.
ResetTransform Restablece la propiedad Transform en
identidad.
RotateTransform Sobrecargado. Aplica a la transformacin
geomtrica local un giro del ngulo
especificado y en el sentido de las agujas del
reloj.
ScaleTransform Sobrecargado. Cambia el tamao de la
transformacin geomtrica local en las
cantidades especificadas. Este mtodo
antepone la matriz de escala a la
transformacin.
SetBlendTriangularShape Sobrecargado. Crea un degradado con un
color central y una disminucin lineal hacia
un color que lo rodea.
SetSigmaBellShape Sobrecargado. Crea una disminucin de
degradado entre el color central y el primer
color que lo rodea basndose en una curva
en forma de campana.
ToString (se hereda de Object) Devuelve un objeto String que representa al
objeto Object actual.
TranslateTransform Sobrecargado. Aplica la conversin
especificada a la transformacin geomtrica
local. Este mtodo antepone la conversin a
la transformacin.
4.1.6.4 Mtodos protegidos
Finalize (se hereda de Object) Reemplazado. Permite que un objeto Object
intente liberar recursos y realizar otras
operaciones de limpieza antes de que el
objeto Object sea reclamado por el
recolector de elementos no utilizados.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.



Textos Universitarios / Serie Docencia
________________________________________________________________________
155
4.1.6.5 El uso de PathGradientBrush en una forma Web

PaintBrushes04.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintBrushes04.aspx?valueH=" +
recHeight + "&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}

ServerPaintBrushes04.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{


public class ServerPaintBrushes04 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}
Jenaro C. Paz
________________________________________________________________________
156

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
GraphicsPath path = new GraphicsPath(new Point[] {
new Point(140, 30),
new Point(235, 70),
new Point(105, 95),
new Point(170, 200),
new Point(50, 220),
new Point(20, 50),
}, new byte[] {
(byte)PathPointType.Start,
(byte)PathPointType.Bezier,
(byte)PathPointType.Bezier,
(byte)PathPointType.Bezier,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
});
/* Segundo ejemplo
GraphicsPath path = new GraphicsPath(new Point[] {
new Point(195, 30),
new Point(217, 99),
new Point(290, 99),
new Point(231, 142),
new Point(253, 210),
new Point(195, 168),
new Point(137, 210),
new Point(159, 142),
new Point(100, 99),
new Point(173, 99),
new Point(195, 30)
}, new byte[] {
(byte)PathPointType.Start,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line
});
Textos Universitarios / Serie Docencia
________________________________________________________________________
157
*/
PathGradientBrush pgbrush = new PathGradientBrush(path);

pgbrush.CenterColor = Color.FromArgb(255, 255, 0, 0);
Color[] colors = {Color.FromArgb(255, 255, 155, 0)};
pgbrush.SurroundColors= colors;
g.FillPath(pgbrush, path);

// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}


Figura 4.6. Pinceles PathGradientBrush





Jenaro C. Paz
________________________________________________________________________
158
Otra aplicacin:

PaintWithBrushes.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
Response.Write("<img border='0'
src='ServerPaintWithBrushes.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "'>");
Response.Write("<p><font color=red>Draw a
Image!</font></p>");
}

ServerPaintWithBrushes.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerPaintWithBrushes : System.Web.UI.Page
{
int w1,h1;
Color bgColor=Color.LightGray;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
Textos Universitarios / Serie Docencia
________________________________________________________________________
159
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);

// +++++++++++++++Begins section related with this Server
//
// Select a pen
Pen bluePen = new Pen(Color.Blue,3);
// Load an Image from root Folder
Bitmap backgroundImage =
new Bitmap (Server.MapPath("colorbars.jpg"));
Brush backgroundBrush = new TextureBrush(backgroundImage);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillRectangle(backgroundBrush, bgRect);
g.FillRectangle(new SolidBrush(Color.FromArgb(180,
Color.White)), bgRect);
//Add a Violet rectangle and a Beige one that overlaps it
g.FillRectangle(new SolidBrush(Color.Violet),
20, 20, 60, 50);
g.FillRectangle(new SolidBrush(Color.FromArgb(180,
Color.Yellow)), 40, 40, 50, 60);

//Add an ellipse that is filled with a translucent hatch
HatchBrush hb = new HatchBrush(HatchStyle.Cross,
Color.Chocolate, Color.FromArgb(100, Color.Yellow));
g.FillEllipse(hb, 180, 20, 160, 80);

//Now create a rectangle filled with a gradient brush
Rectangle r = new Rectangle(260, 120, 100, 100);
LinearGradientBrush lb = new LinearGradientBrush(r,
Color.Green, Color.Turquoise,
LinearGradientMode.ForwardDiagonal);
g.FillRectangle(lb, r);

//Now add a shape drawn with a path gradient brush
GraphicsPath path = new GraphicsPath(new Point[] {
new Point(80, 140),
new Point(145, 200),
new Point(200, 305),
new Point(130, 360),
new Point(50, 290),
new Point(20, 130),
},
new byte[] {
(byte)PathPointType.Start,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
Jenaro C. Paz
________________________________________________________________________
160
(byte)PathPointType.Line,
(byte)PathPointType.Line,
}
);

PathGradientBrush pgb = new PathGradientBrush(path);
pgb.SurroundColors = new Color[] {
Color.Green,
Color.Yellow,
Color.Red,
Color.Blue,
Color.Orange,
Color.Violet,
};

g.FillPath(pgb, path);

//Now add a simple rectangle that has been rotated
g.RotateTransform(-35);
g.FillRectangle(new SolidBrush(Color.Blue),
40, 360, 65, 85);
g.ResetTransform();
g.DrawRectangle(bluePen,bgRect);
//
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}


Textos Universitarios / Serie Docencia
________________________________________________________________________
161

Figura 4.7. Pinceles SolidBrush, TextureBrush, LinearGradientBrush y PathGradientBrush

4.2 Uso de plumas en GDI+

Las plumas son otro objeto importante en GDI+. Como mencionamos anteriormente, se
usan para dibujar lneas y curvas y el contorno de figuras graficas. Una pluma dibuja
lneas y curvas con un ancho especfico y cierto estilo. El objeto Pen provee miembros
para establecer el ancho y estilo de una pluma. Las plumas pueden ser de varios tipos de
lneas continuas o punteadas y de diferente estilo en la manera de rellenar. El proceso de
dibujar una lnea crea una region en la forma de una lnea ensanchada y esa region es
rellenada con un pincel. Las lneas punteadas se representan por estilos dash. Los estilos
para rellenar pueden ser slidos o texturas dependiendo del pincel que se usa para crear la
pluma.
En esta seccin veremos como crear plumas en GDI+; las clases Pen y Pens y como crear
estilos dash, cap y de lnea para las plumas.
La clase Pen representa una pluma en GDI+. Usando el constructor de la clase Pen, se
puede crear un objeto de un objeto Brush o Color especificando el ancho de la pluma.


4.2.1 Clase Pens
21

Requisitos

Espacio de nombres: System.Drawing.Pens

Plumas de todos los colores estndar. No se puede heredar esta clase.

21
http://msdn2.microsoft.com/en-us/library/system.drawing.pens(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
162

4.2.1.1 Propiedades pblicas ( Obtiene Pen definido por el sistema con un
ancho de 1.)
AliceBlue DarkTurquoise LightSkyBlue Peru
AntiqueWhite DarkViolet LightSlateGray Pink
Aqua DeepPink LightSteelBlue Plum
Aquamarine DeepSkyBlue LightYellow PowderBlue
Azure DimGray Lime Purple
Beige DodgerBlue LimeGreen Red
Bisque Firebrick Linen RosyBrown
Black FloralWhite Magenta RoyalBlue
BlanchedAlmond ForestGreen Maroon SaddleBrown
Blue Fuchsia MediumAquamarine Salmon
BlueViolet Gainsboro MediumBlue SandyBrown
Brown GhostWhite MediumOrchid SeaGreen
BurlyWood Gold MediumPurple SeaShell
CadetBlue Goldenrod MediumSeaGreen Sienna
Chartreuse Gray MediumSlateBlue Silver
Chocolate Green MediumSpringGreen SkyBlue
Coral GreenYellow MediumTurquoise SlateBlue
CornflowerBlue Honeydew MediumVioletRed SlateGray
Cornsilk HotPink MidnightBlue Snow
Crimson IndianRed MintCream SpringGreen
Cyan Indigo MistyRose SteelBlue
DarkBlue Ivory Moccasin Tan
DarkCyan Khaki NavajoWhite Teal
DarkGoldenrod Lavender Navy Thistle
DarkGray LavenderBlush OldLace Tomato
DarkGreen LawnGreen Olive Transparent
DarkKhaki LemonChiffon OliveDrab Turquoise
DarkMagenta LightBlue Orange Violet
DarkOliveGreen LightCoral OrangeRed Wheat
DarkOrange LightCyan Orchid White
DarkOrchid LightGoldenrodYellow PaleGoldenrod WhiteSmoke
DarkRed LightGray PaleGreen Yellow
DarkSalmon LightGreen PaleTurquoise YellowGreen
DarkSeaGreen LightPink PaleVioletRed
DarkSlateBlue LightSalmon PapayaWhip
DarkSlateGray LightSeaGreen PeachPuff

La clase Pens como se muestra en la Tabla anterior, tiene propiedades estticas para
todos los colores estndar, que regresan objetos Pen de color. Las siguientes instrucciones
crean tres objetos Pen usando la clase Pens.

Pen myPen1 = Pens.LightGreen;
Pen myPen2 = Pens.Yellow;
Pen myPen3 = Pens.Lavender;

Textos Universitarios / Serie Docencia
________________________________________________________________________
163

4.2.2 Clase Pen
22

Requisitos

Espacio de nombres: System.Drawing.Pen

Define un objeto para dibujar lneas y curvas. No se puede heredar esta clase.

4.2.2.1 Constructores pblicos
Pen (Constructor) Sobrecargado. Inicializa una nueva instancia
de la clase Pen con el color especificado.
4.2.2.2 Propiedades pblicas
Alignment Obtiene o establece la alineacin para este
objeto Pen.
Brush Obtiene o establece el objeto Brush que
determina los atributos de este objeto Pen.
Color Obtiene o establece el color de este objeto
Pen.
CompoundArray Obtiene o establece una matriz de valores
que especifica un lpiz compuesto. Un lpiz
compuesto dibuja una lnea compuesta
formada por lneas y espacios paralelos.
CustomEndCap Obtiene o establece un extremo
personalizado que se utiliza al final de las
lneas dibujadas con este objeto Pen.
CustomStartCap Obtiene o establece un extremo
personalizado que se usa en el comienzo de
las lneas dibujadas con este objeto Pen.
DashCap Obtiene o establece el estilo del extremo
que se utiliza al final de los guiones que
forman las lneas discontinuas dibujadas con
este objeto Pen.
DashOffset Obtiene o establece la distancia desde el
comienzo de una lnea hasta el comienzo de
un modelo de guiones.
DashPattern Obtiene o establece una matriz de guiones y
espacios personalizados.
DashStyle Obtiene o establece el estilo de las lneas
discontinuas dibujadas con este objeto Pen.

22
http://msdn2.microsoft.com/en-us/library/system.drawing.pen(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
164
EndCap Obtiene o establece el estilo de cierre que se
utiliza al final de las lneas dibujadas con
este objeto Pen.
LineJoin Obtiene o establece el estilo de combinacin
de los extremos de dos lneas consecutivas
dibujadas con este objeto Pen.
MiterLimit Obtiene o establece el lmite del grosor de la
combinacin en una esquina en ngulo.
PenType Obtiene el estilo de las lneas dibujadas con
un objeto Pen.
StartCap Obtiene o establece el estilo de cierre que se
utiliza al comienzo de las lneas dibujadas
con este objeto Pen.
Transform Obtiene o establece la transformacin
geomtrica para este objeto Pen.
Width Obtiene o establece el ancho de este objeto
Pen.
4.2.2.3 Mtodos pblicos
Clone Crea una copia exacta de este objeto Pen.
CreateObjRef (se hereda de
MarshalByRefObject)
Crea un objeto que contiene toda la
informacin relevante necesaria para
generar un proxy utilizado para comunicarse
con un objeto remoto.
Dispose Libera todos los recursos utilizados por este
objeto Pen.
Equals (se hereda de Object) Sobrecargado. Determina si dos instancias
de Object son iguales.
GetHashCode (se hereda de Object) Sirve como funcin hash para un tipo
concreto, apropiado para su utilizacin en
algoritmos de hash y estructuras de datos
como las tablas hash.
GetLifetimeService (se hereda de
MarshalByRefObject)
Recupera el objeto de servicio de duracin
actual que controla la directiva de duracin
de esta instancia.
GetType (se hereda de Object) Obtiene el objeto Type de la instancia
actual.
InitializeLifetimeService (se hereda de
MarshalByRefObject)
Obtiene un objeto de servicio de duracin
para controlar la directiva de duracin de
esta instancia.
MultiplyTransform Sobrecargado. Multiplica la matriz de
transformacin de este objeto Pen por la
Matrix especificada.
Textos Universitarios / Serie Docencia
________________________________________________________________________
165
ResetTransform Restablece la matriz de transformacin
geomtrica de este objeto Pen en identidad.
RotateTransform Sobrecargado. Gira la transformacin
geomtrica local el ngulo especificado.
Este mtodo antepone la rotacin a la
transformacin.
ScaleTransform Sobrecargado. Cambia el tamao de la
transformacin geomtrica local en los
factores especificados. Este mtodo
antepone la matriz de escala a la
transformacin.
SetLineCap Establece los valores que determinan el
estilo de cierre que se utiliza para finalizar
las lneas dibujadas con este objeto Pen.
ToString (se hereda de Object) . Devuelve un objeto String que representa al
objeto Object actual.
TranslateTransform Sobrecargado. Convierte la transformacin
geomtrica local en las dimensiones
especificadas. Este mtodo antepone la
conversin a la transformacin.
4.2.2.4 Mtodos protegidos
Finalize Reemplazado. Vea Object.Finalize.
En C# y C++, los finalizadores se expresan
mediante la sintaxis del destructor.
MemberwiseClone (se hereda de Object) Crea una copia superficial del objeto Object
actual.


4.2.2.5 El uso de diferente tipo de plumas en una forma Web

PaintPen01.aspx.cs


private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintPen01.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "&valueC=" + theColor + "'>"+
"</p>");
Jenaro C. Paz
________________________________________________________________________
166
}

ServerPaintPen01.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{


public class ServerPaintPen01 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
Textos Universitarios / Serie Docencia
________________________________________________________________________
167
SolidBrush blueBrush = new SolidBrush(Color.Blue);
HatchBrush hatchBrush =
new HatchBrush(HatchStyle.DashedVertical,
Color.Yellow, Color.Green);
// Create a pen from a solid brush with
// width 7
Pen pn1 = new Pen( blueBrush, 7);
// Create a pen from a hatch brush
Pen pn2 = new Pen(hatchBrush, 8);
// Create a pen from a Color structure
Pen pn3 = new Pen(Color.Red,5);
// Draw a line, ellipse, and rectangle
g.DrawLine(pn1, new Point(40, 40),
new Point(220, 220));
g.DrawEllipse(pn2, 20, 50, 160, 100);
g.DrawRectangle(pn3, 40, 90, 180, 100);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code
}
}




Figura 4.8. Plumas slidas y HatchBrush
PaintPen02.aspx.cs
Jenaro C. Paz
________________________________________________________________________
168


private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPaintPen02.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "&valueC=" + theColor + "'>"+
"</p>");
}

ServerPaintPen02.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
public class ServerPaintPen02 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}
public MemoryStream canvasAndImage()
{
Textos Universitarios / Serie Docencia
________________________________________________________________________
169
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
Bitmap bitmap = new Bitmap(Server.MapPath("Textura.png"));
TextureBrush tbrush = new TextureBrush(bitmap);
Pen texturedPen = new Pen(tbrush, 30);
g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
g.DrawRectangle(texturedPen, 30, 100, 160, 100);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code
}
}



Figura 4.9. Uso de pluma generado con un pincel TextureBrush
4.3 Transformaciones de grficos donde intervienen Plumas

Jenaro C. Paz
________________________________________________________________________
170
Una transformacin es el proceso de cambiar objetos grficos de un estado a otro.
Rotacin, escalamiento, reflexin, translacin y recorte son ejemplos de
transformaciones.

Vimos en el capitulo 3 que la clase Graphics contiene los mtodos:

MultiplyTransform Sobrecargado. Multiplica la transformacin
universal del objeto Graphics y
especificada en el objeto Matrix.
ResetTransform Restablece la matriz de transformacin
universal de este objeto Graphics en la
matriz de identidades.
RotateTransform Sobrecargado. Aplica la rotacin
especificada a la matriz de transformacin
de este objeto Graphics.
ScaleTransform Sobrecargado. Aplica la operacin de
cambio de escala especificada a la matriz de
transformacin de este objeto Graphics,
anteponindola a esta ltima.
TranslateTransform Sobrecargado. Antepone la conversin
especificada a la matriz de transformacin
de este objeto Graphics.

Los cuales permiten llevar a cabo transformaciones sobre objetos grficos que generemos
mediante plumas en un lienzo. A continuacin se presenta el cdigo que nos permite
dibujar una elipse horizontal en color rojo, luego rotarla 45 grados en el sentido de las
manecillas del reloj y volver a dibujarla en color verde, finalmente hacer una translacin
horizontal de 200 pixeles a la derecha y volver a dibujarla en color azul.

C#
Pen pen1 = new Pen(Color.Black,1);
pen1.DashStyle=DashStyle.DashDot;
Pen pen2 = new Pen(Color.Brown,1);
pen1.DashStyle=DashStyle.DashDotDot;
//Draw an Ellipse
g.DrawEllipse(new Pen(Color.Red, 3), 80, 20, 200, 80);
//Draw two lines to the Red Ellipse
g.DrawLine(pen1,0,0,80,60);
g.DrawLine(pen2,0,0,280,60);
// Set world transform of graphics object to rotate 45 degrees.
g.RotateTransform(45.0F);
//Draw an Ellipse
g.DrawEllipse(new Pen(Color.Green, 3), 80, 20, 200, 80);
//Draw two lines to the Green Ellipse
g.DrawLine(pen1,0,0,80,60);
g.DrawLine(pen2,0,0,280,60);
// Then to translate, appending to world transform.
g.TranslateTransform(200.0F, 0.0F, MatrixOrder.Append);
// Draw rotated, translated ellipse to screen.
Textos Universitarios / Serie Docencia
________________________________________________________________________
171
g.DrawEllipse(new Pen(Color.Blue, 3), 80, 20, 200, 80);



Figura 4.10. Rotacin y Translacin de una Elipse horizontal

Obsrvese en la figura anterior, como con la rotacin de 45 grados el punto 1 pasa a ser
el punto 2 y con la translacin de 200 pixeles hacia la derecha el punto 2 pasa a ser el
punto 3.
Como veremos en el Capitulo 9 en donde explicaremos el tema de Transformaciones y
Matrices, cualquier punto (x,y) de la Elipse original se transforma en otro (x,y) de la
Elipse transformada bajo la relacin mostrada a continuacin:


[ ] [ ] 1
1 0 200
0 ) 45 cos( ) 45 (
0 ) 45 ( ) 45 cos(
1 ' ' y x sen
sen
y x
!
!
!
"
#
$
$
$
%
&
' =

Por lo tanto:

x = .7071x - .7071y + 200
y = .7071x + .7071y

Adems de estas transformaciones que podemos realizar al objeto grafico existen otras
que podemos efectuar a un objeto pluma, ya que tambin la clase Pen provee mtodos
para transformar y rotar. El mtodo RotateTransform rota una transformacin un cierto
ngulo de tipo float y como segundo parmetro MatrixOrder que siendo optativo provee
un orden para operaciones de transformacin con matrices. Los valores para dicha
enumeracin son: Append y Prepend. El orden en las matrices es el orden en el cual una
matriz se multiplica por otras.
La diferencia entre Append y Prepend es el orden en la operacin. Por ejemplo, si dos
operaciones estn participando en un proceso, la segunda operacin se llevara a cabo
despus de la primera cuando el orden en las matrices es Append; cuando el orden es
Prepend, la segunda operacin se llevar a cabo primero.
Jenaro C. Paz
________________________________________________________________________
172
El mtodo MultiplyTransform multiplica una matriz de transformacin por una pluma.
Su primer argumento es un objeto Matrix y el segundo argumento opcional es el orden de
la operacin.

El mtodo TranslateTransform de la clase Pen traslada una transformacin por una
dimensin especfica. Este mtodo toma dos valores de tipo float para la translacin en x
e y, luego un tercer parmetro opcional del tipo MatrixOrder.

A continuacin se muestra el cdigo de un ejemplo que hace uso de Transformaciones
sobre la pluma.


TransPens01.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{

string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;


Response.Write("<img border='0'
src='ServerTransPens01.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}


ServerTransPens01.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>
Textos Universitarios / Serie Docencia
________________________________________________________________________
173

public class ServerTransPens01 : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);

bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
// Create a Pen object
Pen Pen1 = new Pen(Color.Violet, 5);
Pen Pen2 = new Pen(Color.YellowGreen, 5);
// Apply rotate and scale transformations
Pen1.ScaleTransform(4, 1);
Pen2.ScaleTransform(4, 1);
g.DrawEllipse(Pen1, 20, 20, 100, 50);
g.DrawRectangle(Pen2, 20, 120, 100, 50);
Pen1.RotateTransform(45, MatrixOrder.Append);
Pen2.RotateTransform(45, MatrixOrder.Append);
g.DrawEllipse(Pen1, 160, 20, 100, 50);
g.DrawRectangle(Pen2, 160, 120, 100, 50);
Pen1.RotateTransform(45, MatrixOrder.Append);
Pen2.RotateTransform(45, MatrixOrder.Append);
g.DrawEllipse(Pen1, 300, 20, 100, 50);
g.DrawRectangle(Pen2, 300, 120, 100, 50);
// Dispose of objects
Pen1.Dispose();
Pen2.Dispose();
g.Dispose();
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
Jenaro C. Paz
________________________________________________________________________
174
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}



Figura 4.11. Rotacin de plumas para generar imgenes

El siguiente ejemplo hace uso de transformaciones de grficos haciendo uso de los
mtodos de la clase Graphics y en una segunda versin se muestra la forma en que se
puede utilizar la matriz de rotacin para llevar a cabo una transformacin para generar los
ptalos de la flor.


DoFlower.aspx.cs

private void btnGenerar_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
Response.Write("<img border='0'
src='ServerDoFlowerPath.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "'>");
Response.Write("<p><font color=red>Making an Image with <I>Path
and Transform</I>!</font></p>");
Textos Universitarios / Serie Docencia
________________________________________________________________________
175
}


ServerDoFlowerPath.aspx

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerDoFlowerPath : System.Web.UI.Page
{
int w1,h1;
Color bgColor=Color.BlanchedAlmond;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}
public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
/* First Method
int cx=w1;
Jenaro C. Paz
________________________________________________________________________
176
int cy=h1;
g.DrawBezier(new Pen(Color.Green,10),
new Point(cx,cy),
new Point(cx,3*cy/4),
new Point(3*cx/4,cy/4),
new Point(cx/2,cy/2));
float fScale = Math.Min(cx,cy)/2000f;
g.TranslateTransform(cx/2,cy/2);
g.ScaleTransform(fScale,fScale);
GraphicsPath path = new GraphicsPath();
path.AddBezier(new Point(0,0),
new Point(150,150),
new Point(450,150),
new Point(600,0));
path.AddBezier(new Point(600,0),
new Point(450,-150),
new Point(150,-150),
new Point(0,0));
for(int i=0; i < 8; i++)
{
g.FillPath(Brushes.Yellow,path);
g.DrawPath(Pens.Black,path);
g.RotateTransform(360/8);
}
Rectangle rect = new Rectangle(-150, -150, 300, 300);
g.FillEllipse(Brushes.Orange,rect);
g.DrawEllipse(Pens.Black,rect);
*/
//Second Method
int cx=w1;
int cy=h1;
g.DrawBezier(new Pen(Color.Green,10),
new Point(cx,cy),
new Point(cx,3*cy/4),
new Point(3*cx/4,cy/4),
new Point(cx/2,cy/2));
float fScale = Math.Min(cx,cy)/2000f;
g.TranslateTransform(cx/2,cy/2);
g.ScaleTransform(fScale,fScale);
GraphicsPath path = new GraphicsPath();
path.AddBezier(new Point(0,0),
new Point(150,150),
new Point(450,150),
new Point(600,0));
path.AddBezier(new Point(600,0),
new Point(450,-150),
new Point(150,-150),
new Point(0,0));
//---------------[using Matrix]-------------------\\
Matrix m = new Matrix(); //This is the Diagonal
m.Rotate(45);
for(int i=0; i < 8; i++)
{
g.FillPath(Brushes.Yellow,path);
g.DrawPath(Pens.Black,path);
path.Transform(m);
}
Textos Universitarios / Serie Docencia
________________________________________________________________________
177
//---------------[/using Matrix]------------------\\

Rectangle rect = new Rectangle(-150, -150, 300, 300);
g.FillEllipse(Brushes.Orange,rect);
g.DrawEllipse(Pens.Black,rect);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}







Figura 4.12. Trayectorias Bezier y rotaciones para generar imgenes



Jenaro C. Paz
________________________________________________________________________
178
En este otro ejemplo se hace uso tambin de transformaciones de grficos mostrando
tambin la forma en que se puede utilizar la matriz de rotacin para llevar a cabo la
transformacin grafica de los cuadrilteros de la estrella.

DoStar.aspx.cs

private void btnGenerar_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
Response.Write("<img border='0'
src='ServerDoStarPath.aspx?valueH=" + recHeight +
"&valueW=" + recWidth + "'>");
Response.Write("<p><font color=red>Making an Image with <I>Path
and Transform</I>!</font></p>");
}


ServerDoStarPath.aspx

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerDoStarPath : System.Web.UI.Page
{
int w1,h1;
Color bgColor=Color.BlanchedAlmond;
private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}
Textos Universitarios / Serie Docencia
________________________________________________________________________
179
public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
int cx=w1;
int cy=h1;
double L=500.0f;
double M=184.0f;
double ang = 54.0f*Math.PI/180.0f;
float cosang =(float)Math.Cos(ang);
float sinang =(float)Math.Sin(ang);
float Msinang = (float)M*sinang;
float Mcosang = (float)M*cosang;
float fScale = Math.Min(cx,cy)/1200f;
float Mf=(float)M;
float Lf =(float)L;
g.TranslateTransform(cx/2,cy/2);
g.ScaleTransform(fScale,fScale);
GraphicsPath path = new GraphicsPath();
path.AddLine(0.0f,0.0f,-Mcosang, -Msinang);
path.AddLine(-Mcosang, -Msinang,0.0f,-Lf);
path.AddLine(0.0f,-Lf,Mcosang,-Msinang);
path.AddLine(Mcosang,-Msinang,0.0f,0.0f);
//---------------[using Matrix]-------------------\\
Matrix m = new Matrix(); //This is the Diagonal
m.Rotate(72);

for(int i=0; i < 5; i++)
{
g.FillPath(Brushes.Yellow,path);
g.DrawPath(Pens.Black,path);
path.Transform(m);
}
//---------------[/using Matrix]-------------------\\
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}

Web Form Designer generated code

}
}

Jenaro C. Paz
________________________________________________________________________
180




Figura 4.13. Dibujo de cuadrilteros y Rotaciones
Para generar la estrella


4.4 Transformaciones de grficos donde intervienen Pinceles

Las clases TextureBrush, LinearGradientBrush y PathGradientBrush representadas en la
Tabla siguiente por X_Brush contienen como ya vimos los siguientes mtodos de
transformacin que aunque no se utilizan muy a menudo pueden servir para algn fin
prctico

MultiplyTransform Sobrecargado. Multiplica el objeto Matrix
que representa la transformacin geomtrica
local de este objeto X_Brush por el objeto
Matrix especificado, en el orden indicado
ResetTransform Restablece la propiedad Transform de este
objeto X_Brush en identidad.
RotateTransform Sobrecargado. Aplica la rotacin
especificada a la matriz de transformacin
de este objeto X_Brush.
ScaleTransform Sobrecargado. Cambia el tamao de la
transformacin geomtrica local de este
objeto X_Brush en la cantidad especificada.
Este mtodo antepone la matriz de escala a
la transformacin.
Textos Universitarios / Serie Docencia
________________________________________________________________________
181
TranslateTransform Sobrecargado. Desplaza la transformacin
geomtrica local de este objeto X_Brush en
las dimensiones y en el orden especificados.

En las siguientes secciones presentamos algunas aplicaciones donde se utilizan
transformaciones al objeto Graphics as como a los diferentes pinceles con que se dibuja.


4.4.1 Transformaciones para TextureBrush

TextureBTrans.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;
Response.Write("<img border='0'
src='ServerTextureBTrans.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}



ServerTextureBTrans.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerTextureBTrans : System.Web.UI.Page
{
int w1,h1;
Jenaro C. Paz
________________________________________________________________________
182
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);

bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
// Create a TextureBrush object
TextureBrush txtrBrush = new TextureBrush(
new Bitmap(Server.MapPath("flowers3.png")));
// Rotate the texture image by 90 degrees
txtrBrush.RotateTransform(90,
MatrixOrder.Prepend);
// Scale operation
txtrBrush.ScaleTransform(2, 1,
MatrixOrder.Prepend);
// Fill a rectangle with texture brush
g.TranslateTransform(180,0,MatrixOrder.Append);
g.FillRectangle(txtrBrush, 0, 0, 192, 332);
// Reset transformation
txtrBrush.ResetTransform();
// Fill rectangle after resetting transformation
//
g.ResetTransform();
g.FillRectangle(txtrBrush, 0, 0, 166, 192);
txtrBrush.ResetTransform();
txtrBrush.RotateTransform(180,
MatrixOrder.Prepend);
g.TranslateTransform(0,192,MatrixOrder.Append);
g.FillRectangle(txtrBrush, 0, 0, 166, 192);
// Dispose of objects
txtrBrush.Dispose();
g.Dispose();
// +++++++++++++++Ends section related with this Server
Textos Universitarios / Serie Docencia
________________________________________________________________________
183
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code

}
}





Figura 4.14. Transformaciones para TextureBrush



4.4.2 Transformaciones para LinearGradientBrush

LinearGradBTrans.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{

string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;


Response.Write("<img border='0'
src='ServerLinearGradTrans.aspx?valueH=" + recHeight +
Jenaro C. Paz
________________________________________________________________________
184
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}


ServerLinearGradTrans.aspx.cs


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerLinearGradBTrans : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);

bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
Textos Universitarios / Serie Docencia
________________________________________________________________________
185
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
// Create a LinearGradientBrush object
Rectangle rect = new Rectangle(0, 0, 100, 100);
LinearGradientBrush lgBrush =
new LinearGradientBrush(
rect, Color.Red, Color.Orange,0.0f,true);
Matrix M = new Matrix(.7071f,.7071f,-
.7071f,.7071f,0.0f,0.0f);
// Multiply transformation
lgBrush.MultiplyTransform(M, MatrixOrder.Prepend);
// Draw a rectangle after transformation
g.FillRectangle(lgBrush, 0,0,200,200);
// Reset transformation
lgBrush.ResetTransform();
// Draw a rectangle after reset transformation
g.FillRectangle(lgBrush, 200, 0, 200, 200);
//Draw a white line to separate
g.DrawLine(Pens.White,new Point(200,0),new Point(200,200));
// Dispose of objects
lgBrush.Dispose();
g.Dispose();
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code

}
}


Jenaro C. Paz
________________________________________________________________________
186


Figura 4.15. Transformaciones para LinearGradientBrush

Enseguida se muestra el cdigo de una aplicacin donde las transformaciones solo se
llevan a cabo con los mtodos de la clase Graphics

LinearGradBrushes.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{

string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;


Response.Write("<img border='0'
src='ServerLGBrushes.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}


ServerLGBrushes.aspx.cs


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
Textos Universitarios / Serie Docencia
________________________________________________________________________
187
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerLGBrushes : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);

bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
Rectangle rect = new Rectangle(0,0,150,100);
LinearGradientBrush lbrush = new LinearGradientBrush(rect,
Color.Wheat, Color.Orange,
LinearGradientMode.ForwardDiagonal);
g.RotateTransform(-60);
g.ScaleTransform(1,2);
g.TranslateTransform(-140,100);
g.FillRectangle(lbrush,rect);
g.ResetTransform();
g.FillRectangle(lbrush,rect);
Jenaro C. Paz
________________________________________________________________________
188
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code

}
}





Figura 4.16. Transformaciones para el objeto Graphics
asociado con LinearGradientBrush


4.4.3 Transformaciones para PathGradientBrush

PathGradientBrushes.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;
Response.Write("<img border='0'
src='ServerPathGradientBrushes.aspx?valueH=" +
recHeight + "&valueW=" + recWidth +
Textos Universitarios / Serie Docencia
________________________________________________________________________
189
"&valueC=" + theColor + "'>"+ "</p>");
}

ServerPathGradientBrushes.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerPathGradientBrushes : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);

bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
Jenaro C. Paz
________________________________________________________________________
190
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
/*
GraphicsPath path = new GraphicsPath(new Point[] {
new Point(140, 30),
new Point(235, 70),
new Point(105, 95),
new Point(170, 200),
new Point(50, 220),
new Point(20, 50),
}, new byte[] {
(byte)PathPointType.Start,
(byte)PathPointType.Bezier,
(byte)PathPointType.Bezier,
(byte)PathPointType.Bezier,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
});
*/
// Segundo ejemplo
GraphicsPath path = new GraphicsPath(new Point[] {
new Point(195, 30),
new Point(217, 99),
new Point(290, 99),
new Point(231, 142),
new Point(253, 210),
new Point(195, 168),
new Point(137, 210),
new Point(159, 142),
new Point(100, 99),
new Point(173, 99),
new Point(195, 30)
}, new byte[] {
(byte)PathPointType.Start,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line
});

PathGradientBrush pgbrush = new PathGradientBrush(path);
pgbrush.CenterColor = Color.FromArgb(255, 255, 0, 0);
Color[] colors = {Color.FromArgb(255, 255, 155, 0)};
pgbrush.SurroundColors= colors;

g.TranslateTransform(195.0F,115.31034482758620689655172413793F);
g.RotateTransform(36);
g.TranslateTransform(40,40);
g.ScaleTransform(0.5F,0.5F);
g.FillPath(pgbrush, path);
Textos Universitarios / Serie Docencia
________________________________________________________________________
191
g.ResetTransform();
g.FillPath(pgbrush, path);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code

}
}





Figura 4.17. Transformaciones del objeto Graphics
asociado con PathGradientBrush



PathGradBTrans.aspx.cs


private void btnBuild_Click(object sender, System.EventArgs e)
{
string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;

Response.Write("<img border='0'
src='ServerPathGradBTrans.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
Jenaro C. Paz
________________________________________________________________________
192
"&valueC=" + theColor + "'>"+ "</p>");
}



ServerPathGradBTrans.aspx


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerPathGradBTrans : System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
Textos Universitarios / Serie Docencia
________________________________________________________________________
193
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
GraphicsPath path = new GraphicsPath();
// Create a rectangle and add it to path
Rectangle rect = new Rectangle(20, 20, 100, 100);
path.AddRectangle(rect);
// Create a path gradient brush
PathGradientBrush pgBrush =
new PathGradientBrush(path.PathPoints);
// Set its center and surrounding colors
pgBrush.CenterColor = Color.Yellow;
pgBrush.SurroundColors = new Color[] {Color.Red};
g.FillRectangle(pgBrush, 20, 20, 400, 400);
pgBrush.CenterColor = Color.Green;
pgBrush.SurroundColors = new Color[] {Color.Blue};
// Create matrix
Matrix M = new Matrix();
// Translate
M.Translate(150.0f, 70.0f, MatrixOrder.Prepend);
// Rotate
M.Rotate(20.0f, MatrixOrder.Prepend);
// Scale
M.Scale(1f, 2.0f, MatrixOrder.Prepend);
// Shear
M.Shear(.5f, 0.1f, MatrixOrder.Prepend);
// Apply matrix to the brush
pgBrush.MultiplyTransform(M);
// Use brush after transformation
// to fill a rectangle
g.FillRectangle(pgBrush, 20, 20, 400, 400);
// Dispose of objects
pgBrush.Dispose();
g.Dispose();
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}


Web Form Designer generated code

}
}



Jenaro C. Paz
________________________________________________________________________
194


Figura 4.18. Transformaciones del objeto PathGradientBrush







4.5 Plumas y pinceles del Sistema

Las plumas y pinceles del sistema, se usan para dibujar y pintar usando colores del
sistema. La forma en que plumas y pinceles pueden crearse es usando la clase
SystemColors.

4.5.1 Colores del Sistema

SystemColors representa en GDI+ a los colores del sistema, proveyendo las propiedades
publicas para que usted pueda hacerlo. La manera para crear plumas de la clase
SystemPens y pinceles de la clase SystemBrushes la veremos mas adelante, despus de
presentar a esta clase.


Textos Universitarios / Serie Docencia
________________________________________________________________________
195
4.5.1.1 Clase SystemColors
23

Requisitos

Espacio de nombres: System.Drawing
4.5.1.1.1 Propiedades pblicas
ActiveBorder Obtiene una estructura Color que es el color
del borde de la ventana activa.
ActiveCaption

Obtiene una estructura Color que es el color
del fondo de la barra de ttulo de la ventana
activa.
ActiveCaptionText

Obtiene una estructura Color que es el color
del texto de la barra de ttulo de la ventana
activa.
AppWorkspace

Obtiene una estructura Color que es el color
del rea de trabajo de la aplicacin. El rea
de trabajo de la aplicacin es el rea en una
vista de varios documentos que no ocupan
dichos documentos.
Control Obtiene una estructura Color que es el color
de la superficie de un elemento 3D.
ControlDark Obtiene una estructura Color que es el color
de la sombra de un elemento 3D. El color de
la sombra se aplica a las partes de los
elementos en tres dimensiones que se
encuentran en la zona alejada de la fuente de
luz.
ControlDarkDark

Obtiene una estructura Color que es el color
de la sombra oscura de un elemento 3D. El
color de la sombra oscura se aplica a las
partes de los elementos 3D que tienen el
color ms oscuro.
ControlLight

Obtiene una estructura Color que es el color
claro de un elemento 3D. El color claro se
aplica a las partes de los elementos 3D
expuestos a la fuente de luz.
ControlLightLight

Obtiene una estructura Color que es el color
resaltado de un elemento 3D. El color
resaltado se aplica a las partes de los
elementos 3D que tienen el color ms claro.
ControlText Obtiene una estructura Color que es el color

23
http://msdn2.microsoft.com/en-us/library/system.drawing.systemcolors(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
196
del texto de un elemento 3D.
Desktop Obtiene una estructura Color que es el color
del escritorio.
GrayText

Obtiene una estructura Color que es el color
del texto atenuado. Los elementos de una
lista que no estn habilitados se muestran en
texto atenuado.
Highlight

Obtiene una estructura Color que es el color
del fondo de los elementos seleccionados.
Incluye elementos de men seleccionados
adems del texto seleccionado. Por ejemplo,
la estructura Color puede ser el color
utilizado para el fondo de los elementos
seleccionados de un cuadro de lista.
HighlightText

Obtiene una estructura Color que es el color
del texto de los elementos seleccionados.
Por ejemplo, la estructura Color puede ser el
color utilizado para el texto de los
elementos seleccionados de un cuadro de
lista.
HotTrack

Obtiene una estructura Color que es el color
utilizado para determinar un elemento del
que se hace un seguimiento completo. Si se
hace un slo clic en un elemento del que se
hace un seguimiento completo, el elemento
se ejecuta.
InactiveBorder Obtiene una estructura Color que es el color
del borde de una ventana inactiva.
InactiveCaption

Obtiene una estructura Color que es el color
del fondo de la barra de ttulo de una
ventana inactiva.
InactiveCaptionText

Obtiene una estructura Color que es el color
del texto de la barra de ttulo de una ventana
inactiva.
Info

Obtiene una estructura Color que es el color
del fondo de una informacin sobre
herramientas.
InfoText

Obtiene una estructura Color que es el color
del texto de una informacin sobre
herramientas.
Menu Obtiene una estructura Color que es el color
del fondo de un men.
MenuText Obtiene una estructura Color que es el color
del texto de un men.
Textos Universitarios / Serie Docencia
________________________________________________________________________
197
ScrollBar Obtiene una estructura Color que es el color
del fondo de una barra de desplazamiento.
Window Obtiene una estructura Color que es el color
del fondo del rea de cliente de una ventana.
WindowFrame Obtiene una estructura Color que es el color
del marco de una ventana.
WindowText Obtiene una estructura Color que es el color
del texto del rea de cliente de una ventana.




























4.5.2 Plumas del Sistema
Cada una de las propiedades de la clase SystemPens es un objeto Pen que es del color de
un elemento de presentacin de Windows y es de un ancho de 1 pixel.
4.5.2.1 Clase SystemPens
24

Requisitos

24
http://msdn2.microsoft.com/en-us/library/system.drawing.systempens(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
198

Espacio de nombres: System.Drawing

4.5.2.2 Propiedades pblicas
ActiveCaptionText Obtiene un objeto Pen que es el color del
texto de la barra de ttulo de la ventana
activa.
Control Obtiene un objeto Pen que es el color de
superficie de un elemento 3D.
ControlDark Obtiene un objeto Pen que es el color de la
sombra de un elemento 3D. El color de la
sombra se aplica a las partes de los
elementos en tres dimensiones que se
encuentran en la zona alejada de la fuente de
luz.
ControlDarkDark Obtiene un objeto Pen que es el color de la
sombra oscura de un elemento 3D. El color
de la sombra oscura se aplica a las partes de
los elementos 3D que tienen el color ms
oscuro.
ControlLight Obtiene un objeto Pen que es el color claro
de un elemento 3D. El color claro se aplica
a las partes de los elementos 3D expuestos a
la fuente de luz.
ControlLightLight Obtiene un objeto Pen que es el color
resaltado de un elemento 3D. El color
resaltado se aplica a las partes de los
elementos 3D que tienen el color ms claro.
ControlText Obtiene un objeto Pen que es el color del
texto de un elemento 3D.
GrayText Obtiene un objeto Pen que es el color del
texto atenuado. Los elementos de una lista
que no estn habilitados se muestran en
texto atenuado.
Highlight Obtiene un objeto Pen que es el color del
fondo de los elementos seleccionados.
Incluye elementos de men seleccionados
adems del texto seleccionado. Por ejemplo,
el lpiz puede ser del color utilizado para el
fondo de los elementos seleccionados de un
cuadro de lista.
HighlightText Obtiene un objeto Pen que es el color del
Textos Universitarios / Serie Docencia
________________________________________________________________________
199
texto de los elementos seleccionados.
Incluye elementos de men seleccionados
adems del texto seleccionado. Por ejemplo,
el lpiz puede ser del color utilizado para el
texto de los elementos seleccionados de un
cuadro de lista.
InactiveCaptionText Obtiene un objeto Pen que es el color del
texto de la barra de ttulo de una ventana
inactiva.
InfoText Obtiene un objeto Pen que es el color del
texto de una informacin sobre
herramientas.
MenuText Obtiene un objeto Pen que es el color del
texto de un men.
WindowFrame Obtiene un objeto Pen que es el color del
marco de una ventana.
WindowText Obtiene un objeto Pen que es el color del
texto del rea de cliente de una ventana.

La manera de crear una pluma utilizando la clase SystemPens se proporciona en el
siguiente segmento de cdigo

C#
Pen myPen = SystemPens.FromSystemColor(SystemColors.GrayText);


4.5.3 Pinceles del Sistema

Cada una de las propiedades de la clase SystemBrushes es un objeto SolidBrush que es el
color de un elemento de presentacin de Windows.


4.5.3.1 Clase SystemBrushes
25

Requisitos

Espacio de nombres: System.Drawing

4.5.3.1.1 Propiedades pblicas
ActiveBorder Obtiene un objeto SolidBrush que es el
color del borde de la ventana activa.
ActiveCaption Obtiene un objeto SolidBrush que es el

25
http://msdn2.microsoft.com/en-us/library/system.drawing.systembrushes(VS.80).aspx
Junio 3 de 2006
Jenaro C. Paz
________________________________________________________________________
200
color del fondo de la barra de ttulo de la
ventana activa.
ActiveCaptionText Obtiene un objeto SolidBrush que es el
color del texto de la barra de ttulo de la
ventana activa.
AppWorkspace Obtiene un objeto SolidBrush que es el
color del rea de trabajo de la aplicacin. El
rea de trabajo de la aplicacin es el rea en
una vista de varios documentos que no
ocupan dichos documentos.
Control Obtiene un objeto SolidBrush que es el
color de la superficie de un elemento en tres
dimensiones.
ControlDark Obtiene un objeto SolidBrush que es el
color de la sombra de un elemento en tres
dimensiones. El color de la sombra se aplica
a las partes de los elementos en tres
dimensiones que se encuentran en la zona
alejada de la fuente de luz.
ControlDarkDark Obtiene un objeto SolidBrush que es el
color de la sombra oscura de un elemento
3D. El color de la sombra oscura se aplica a
las partes de los elementos 3D que tienen el
color ms oscuro.
ControlLight Obtiene un objeto SolidBrush que es el
color claro de un elemento 3D. El color
claro se aplica a las partes de los elementos
3D expuestos a la fuente de luz.
ControlLightLight Obtiene un objeto SolidBrush que es el
color resaltado de un elemento en tres
dimensiones. El color resaltado se aplica a
las partes de los elementos 3D que tienen el
color ms claro.
ControlText Obtiene un objeto SolidBrush que es el
color del texto de un elemento 3D.
Desktop Obtiene un objeto SolidBrush que es el
color del escritorio.
Highlight Obtiene un objeto SolidBrush que es el
color del fondo de los elementos
seleccionados. Incluye elementos de men
seleccionados adems del texto
seleccionado. Por ejemplo, el pincel puede
ser del color utilizado para el fondo de los
elementos seleccionados de un cuadro de
Textos Universitarios / Serie Docencia
________________________________________________________________________
201
lista.
HighlightText Obtiene un objeto SolidBrush que es el
color del texto de los elementos
seleccionados. Incluye elementos de men
seleccionados adems del texto
seleccionado. Por ejemplo, el pincel puede
ser del color utilizado para el texto de los
elementos seleccionados de un cuadro de
lista.
HotTrack Obtiene un objeto SolidBrush que es el
color utilizado para determinar un elemento
del que se hace un seguimiento completo. Si
se hace un slo clic en un elemento del que
se hace un seguimiento completo, el
elemento se ejecuta.
InactiveBorder Obtiene un objeto SolidBrush que es el
color del borde de una ventana inactiva.
InactiveCaption Obtiene un objeto SolidBrush que es el
color del fondo de la barra de ttulo de una
ventana inactiva.
Info Obtiene un objeto SolidBrush que es el
color del fondo de una informacin sobre
herramientas.
Menu Obtiene un objeto SolidBrush que es el
color del fondo de un men.
ScrollBar Obtiene un objeto SolidBrush que es el
color del fondo de una barra de
desplazamiento.
Window Obtiene un objeto SolidBrush que es el
color del fondo del rea de cliente de una
ventana.
WindowText Obtiene un objeto SolidBrush que es el
color del texto del rea de cliente de una
ventana.

C#
SolidBrush myBrush = (SolidBrush)
SystemBrushes.FromSystemColor(SystemColors.InactiveCaption);

SystemPenPencil.aspx.cs

private void btnBuild_Click(object sender, System.EventArgs e)
{
Jenaro C. Paz
________________________________________________________________________
202

string recHeight = txtHeight.Text;
string recWidth = txtWidth.Text;
string theColor = ColorList.SelectedItem.Text ;


Response.Write("<img border='0'
src='ServerSystemPenPencil.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}

ServerSystemPenPencil.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization ;

namespace JCPGraphics
{
/// <summary>
/// Summary description for rectServer.
/// </summary>

public class ServerSystemPenPencil: System.Web.UI.Page
{
int w1,h1;
Color bgColor;

private void Page_Load(object sender, System.EventArgs e)
{
w1 = UInt16.Parse(Request.QueryString["valueW"]);
h1 = UInt16.Parse(Request.QueryString["valueH"]);
bgColor=Color.FromName(Request.QueryString["valueC"]);
// Create a Stream in memory to save the image
MemoryStream memStream = canvasAndImage();
Response.Clear();
// Send the memory image to Browser in binary mode
Textos Universitarios / Serie Docencia
________________________________________________________________________
203
memStream.WriteTo(Response.OutputStream);
}

public MemoryStream canvasAndImage()
{
// Define a Rectangle to be the BG rectangle
Rectangle bgRect = new Rectangle(0,0,w1,h1);
// The bitmap Object used to work with images defined by
// pixel data
Bitmap pixelImage = new Bitmap(w1,h1);
// 1) Will be used to build the new Graphics object
// 2) Whatever you do with the Graphics object you afect
// the image object!
Graphics g = Graphics.FromImage(pixelImage);
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor), bgRect);
// +++++++++++++++Begins section related with this Server
//
// Create a pen using SystemPens
Pen pn = SystemPens.FromSystemColor(SystemColors.GrayText);
// Create a brush using SystemBrushes
SolidBrush brush =
(SolidBrush)SystemBrushes.FromSystemColor
(SystemColors.InactiveCaption);
// Draw lines and rectangles
g.DrawLine(pn, 20, 20, 20, 100);
g.DrawLine(pn, 20, 20, 100, 20);
g.DrawLine(pn,20,100,100,100);
g.DrawLine(pn,100,20,100,100);
g.FillRectangle(brush, 30, 30, 60, 60);
// +++++++++++++++Ends section related with this Server
MemoryStream aStream = new MemoryStream();
pixelImage.Save(aStream,ImageFormat.Png);
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code

}
}

Jenaro C. Paz
________________________________________________________________________
204


Figura 4.19. Trabajando con plumas y pinceles del Sistema

También podría gustarte