Escolar Documentos
Profissional Documentos
Cultura Documentos
________________________________________________________________________
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.
http://msdn2.microsoft.com/en-us/library/system.drawing.brush(VS.80).aspx
Junio 3 de 2006
135
Jenaro C. Paz
________________________________________________________________________
Dispose .
Equals (se hereda de Object)
GetHashCode (se hereda de Object)
http://msdn2.microsoft.com/en-us/library/system.drawing.solidbrush(VS.80).aspx
Junio 3 de 2006
136
Jenaro C. Paz
________________________________________________________________________
actual.
WrapMode
17
http://msdn2.microsoft.com/en-us/library/system.drawing.texturebrush(VS.80).aspx
Junio 3 de 2006
138
ResetTransform
RotateTransform
ScaleTransform
139
Jenaro C. Paz
________________________________________________________________________
TextureBrush en las dimensiones y en el
orden especificados.
PaintBrushes01.aspx.cs
using System;
140
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
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>");
}
}
141
Jenaro C. Paz
________________________________________________________________________
}
ServerPaintBrushes01.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
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
142
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.hatchbrush(VS.80).aspx
Junio 3 de 2006
143
Jenaro C. Paz
________________________________________________________________________
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.
ForegroundColor
HatchStyle
144
ServerPaintBrushes02.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace JCPGraphics
{
public class ServerPaintBrushes02 : System.Web.UI.Page
145
Jenaro C. Paz
________________________________________________________________________
{
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
}
}
146
Cross
DashedDownwardDiagonal
DiagonalCross
Horizontal
LightDownwardDiagonal
Min
Percent10
DarkDownwardDiagonal
DashedHorizontal
Divot
HorizontalBrick
LightHorizontal
NarrowHorizontal
Percent20
DarkHorizontal
DashedUpwardDiagonal
DottedDiamond
LargeCheckerBoard
LightUpwardDiagonal
NarrowVertical
Percent25
DarkUpwardDiagonal
DashedVertical
DottedGrid
LargeConfetti
LightVertical
OutlinedDiamond
Percent30
Percent50
Percent90
SmallGrid
Wave
Percent60
Plaid
SolidDiamond
Weave
Percent70
Shingle
Sphere
WideDownwardDiagonal
Percent75
SmallCheckerBoard
Trellis
WideUpwardDiagonal
19
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.lineargradientbrush(VS.80).aspx
Junio 3 de 2006
147
Jenaro C. Paz
________________________________________________________________________
GammaCorrection
InterpolationColors
LinearColors
Rectangle
Transform
WrapMode
ResetTransform
RotateTransform
ScaleTransform
SetBlendTriangularShape
SetSigmaBellShape
esta instancia.
Sobrecargado. Multiplica el objeto Matrix
que representa la trasformacin geomtrica
local de este objeto LinearGradientBrush
por el objeto Matrix anteponindole el
objeto Matrix especificado.
Restablece la propiedad Transform en
identidad.
Sobrecargado. Gira la transformacin
geomtrica local la cantidad especificada.
Este mtodo antepone la rotacin a la
transformacin.
Sobrecargado. Cambia el tamao de la
transformacin geomtrica local en las
cantidades especificadas. Este mtodo
antepone la matriz de escala a la
transformacin.
Sobrecargado. Crea un degradado lineal con
un color central y una disminucin lineal
hacia un nico color en ambos extremos.
Sobrecargado. Crea una disminucin de
degradado basada en una curva en forma de
campana.
Devuelve un objeto String que representa al
objeto Object actual.
Sobrecargado. Convierte la transformacin
geomtrica local en las dimensiones
especificadas. Este mtodo antepone la
conversin a la transformacin.
Jenaro C. Paz
________________________________________________________________________
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
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
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()
150
LinearGradientMode
BackwardDiagonal
ForwardDiagonal
Horizontal
Vertical
151
Jenaro C. Paz
________________________________________________________________________
CenterColor
20
http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.pathgradientbrush(VS.80).aspx
Junio 3 ,de 2006
152
Rectangle
SurroundColors
Transform
WrapMode
153
Jenaro C. Paz
________________________________________________________________________
ResetTransform
RotateTransform
ScaleTransform
SetBlendTriangularShape
SetSigmaBellShape
154
ServerPaintBrushes04.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
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);
}
155
Jenaro C. Paz
________________________________________________________________________
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
});
156
157
Jenaro C. Paz
________________________________________________________________________
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
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Drawing.Drawing2D;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
158
159
Jenaro C. Paz
________________________________________________________________________
(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
}
}
160
http://msdn2.microsoft.com/en-us/library/system.drawing.pens(VS.80).aspx
Junio 3 de 2006
161
Jenaro C. Paz
________________________________________________________________________
ancho de 1.)
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Azure
Beige
Bisque
Black
BlanchedAlmond
Blue
BlueViolet
Brown
BurlyWood
CadetBlue
Chartreuse
Chocolate
Coral
CornflowerBlue
Cornsilk
Crimson
Cyan
DarkBlue
DarkCyan
DarkGoldenrod
DarkGray
DarkGreen
DarkKhaki
DarkMagenta
DarkOliveGreen
DarkOrange
DarkOrchid
DarkRed
DarkSalmon
DarkSeaGreen
DarkSlateBlue
DarkSlateGray
DarkTurquoise
DarkViolet
DeepPink
DeepSkyBlue
DimGray
DodgerBlue
Firebrick
FloralWhite
ForestGreen
Fuchsia
Gainsboro
GhostWhite
Gold
Goldenrod
Gray
Green
GreenYellow
Honeydew
HotPink
IndianRed
Indigo
Ivory
Khaki
Lavender
LavenderBlush
LawnGreen
LemonChiffon
LightBlue
LightCoral
LightCyan
LightGoldenrodYellow
LightGray
LightGreen
LightPink
LightSalmon
LightSeaGreen
LightSkyBlue
LightSlateGray
LightSteelBlue
LightYellow
Lime
LimeGreen
Linen
Magenta
Maroon
MediumAquamarine
MediumBlue
MediumOrchid
MediumPurple
MediumSeaGreen
MediumSlateBlue
MediumSpringGreen
MediumTurquoise
MediumVioletRed
MidnightBlue
MintCream
MistyRose
Moccasin
NavajoWhite
Navy
OldLace
Olive
OliveDrab
Orange
OrangeRed
Orchid
PaleGoldenrod
PaleGreen
PaleTurquoise
PaleVioletRed
PapayaWhip
PeachPuff
Peru
Pink
Plum
PowderBlue
Purple
Red
RosyBrown
RoyalBlue
SaddleBrown
Salmon
SandyBrown
SeaGreen
SeaShell
Sienna
Silver
SkyBlue
SlateBlue
SlateGray
Snow
SpringGreen
SteelBlue
Tan
Teal
Thistle
Tomato
Transparent
Turquoise
Violet
Wheat
White
WhiteSmoke
Yellow
YellowGreen
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;
162
CustomEndCap
CustomStartCap
DashCap
DashOffset
DashPattern
DashStyle
22
http://msdn2.microsoft.com/en-us/library/system.drawing.pen(VS.80).aspx
Junio 3 de 2006
163
Jenaro C. Paz
________________________________________________________________________
EndCap
LineJoin
MiterLimit
PenType
StartCap
Transform
Width
Dispose
Equals (se hereda de Object)
GetHashCode (se hereda de Object)
164
ScaleTransform
SetLineCap
Finalize
4.2.2.5
PaintPen01.aspx.cs
165
Jenaro C. Paz
________________________________________________________________________
}
ServerPaintPen01.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
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
//
166
PaintPen02.aspx.cs
167
Jenaro C. Paz
________________________________________________________________________
ServerPaintPen02.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
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()
{
168
169
Jenaro C. Paz
________________________________________________________________________
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
ResetTransform
RotateTransform
ScaleTransform
TranslateTransform
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.
170
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:
[x'
y 1]
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.
171
Jenaro C. Paz
________________________________________________________________________
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
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
172
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
173
Jenaro C. Paz
________________________________________________________________________
// Bmp, Jpeg, Png, Gif
return aStream;
}
Web Form Designer generated code
}
}
174
ServerDoFlowerPath.aspx
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
175
Jenaro C. Paz
________________________________________________________________________
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);
}
176
177
Jenaro C. Paz
________________________________________________________________________
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
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
178
179
Jenaro C. Paz
________________________________________________________________________
4.4
ResetTransform
RotateTransform
ScaleTransform
180
ServerTextureBTrans.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
181
Jenaro C. Paz
________________________________________________________________________
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
182
183
Jenaro C. Paz
________________________________________________________________________
"&valueW=" + recWidth +
"&valueC=" + theColor + "'>"+ "</p>");
}
ServerLinearGradTrans.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
184
185
Jenaro C. Paz
________________________________________________________________________
ServerLGBrushes.aspx.cs
using
using
using
using
using
using
using
using
186
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
187
Jenaro C. Paz
________________________________________________________________________
// +++++++++++++++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
}
}
188
ServerPathGradientBrushes.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
189
Jenaro C. Paz
________________________________________________________________________
// Fill the interior of the bg rectangle
g.FillRectangle(new SolidBrush(bgColor),
// +++++++++++++++Begins section related
/*
GraphicsPath path = new GraphicsPath(new
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
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
});
bgRect);
with this Server
Point[] {
Point[] {
190
PathGradBTrans.aspx.cs
private void
{
string
string
string
Response.Write("<img border='0'
src='ServerPathGradBTrans.aspx?valueH=" + recHeight +
"&valueW=" + recWidth +
191
Jenaro C. Paz
________________________________________________________________________
"&valueC=" + theColor + "'>"+ "</p>");
}
ServerPathGradBTrans.aspx
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
192
193
Jenaro C. Paz
________________________________________________________________________
4.5
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.
194
ActiveCaptionText
AppWorkspace
Control
ControlDark
ControlDarkDark
ControlLight
ControlLightLight
ControlText
23
http://msdn2.microsoft.com/en-us/library/system.drawing.systemcolors(VS.80).aspx
Junio 3 de 2006
195
Jenaro C. Paz
________________________________________________________________________
Desktop
GrayText
Highlight
HighlightText
HotTrack
InactiveBorder
InactiveCaption
InactiveCaptionText
Info
InfoText
Menu
MenuText
196
http://msdn2.microsoft.com/en-us/library/system.drawing.systempens(VS.80).aspx
Junio 3 de 2006
197
Jenaro C. Paz
________________________________________________________________________
Espacio de nombres: System.Drawing
Control
ControlDark
ControlDarkDark
ControlLight
ControlLightLight
ControlText
GrayText
Highlight
HighlightText
198
InactiveCaptionText
InfoText
MenuText
WindowFrame
WindowText
25
http://msdn2.microsoft.com/en-us/library/system.drawing.systembrushes(VS.80).aspx
Junio 3 de 2006
199
Jenaro C. Paz
________________________________________________________________________
ActiveCaptionText
AppWorkspace
Control
ControlDark
ControlDarkDark
ControlLight
ControlLightLight
ControlText
Desktop
Highlight
200
HotTrack
InactiveBorder
InactiveCaption
Info
Menu
ScrollBar
Window
WindowText
lista.
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.
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.
Obtiene un objeto SolidBrush que es el
color del borde de una ventana inactiva.
Obtiene un objeto SolidBrush que es el
color del fondo de la barra de ttulo de una
ventana inactiva.
Obtiene un objeto SolidBrush que es el
color del fondo de una informacin sobre
herramientas.
Obtiene un objeto SolidBrush que es el
color del fondo de un men.
Obtiene un objeto SolidBrush que es el
color del fondo de una barra de
desplazamiento.
Obtiene un objeto SolidBrush que es el
color del fondo del rea de cliente de una
ventana.
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
201
Jenaro C. Paz
________________________________________________________________________
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
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.Web;
System.Web.SessionState;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
System.IO;
System.Drawing.Imaging;
System.Drawing.Drawing2D;
System.Drawing.Text;
System.Globalization ;
namespace
{
///
///
///
JCPGraphics
<summary>
Summary description for rectServer.
</summary>
202
203
Jenaro C. Paz
________________________________________________________________________
204