《C# GDI+ 破境之道》:第一境 GDI+基礎 —— 第二節:畫矩形
有了上一節畫線的基礎,畫矩形的各種邊線就特別好理解了,所以,本節在矩形邊線上,就不做過多的講解了,關注一下畫“隨機矩形”的具體實現就好。與畫線相比較,畫矩形稍微複雜的一點就是在於它多了很多填充的樣式。接下來,我們就來細細品味一番。
同樣,一個窗體專案,窗體的佈局風格與上一節的保持一致:
1 namespace MikeWare.GdiPlus.Rectangles 2 { 3 using System; 4 using System.Collections.Generic; 5 using System.Drawing; 6 using System.Drawing.Drawing2D; 7 using System.Windows.Forms; 8 9 public partial class FormDrawRectangles : Form 10 { 11 private Random random = null; 12 private Color penColor = Color.Transparent; 13 14 public FormDrawRectangles() 15 { 16 InitializeComponent(); 17 random = new Random(DateTime.Now.Millisecond); 18 penColor = GetRandomColor(); 19 } 20 21 private Point GetRandomPoint() 22 { 23 return new Point(random.Next(0, ClientRectangle.Width), random.Next(0, ClientRectangle.Height - pnlToolbox.Height)); 24 } 25 26 private Rectangle GetRandomRectangle() 27 { 28 var pointA = GetRandomPoint(); 29 var pointB = GetRandomPoint(); 30 31 return new Rectangle(Math.Min(pointA.X, pointB.X) 32 , Math.Min(pointA.Y, pointB.Y) 33 , Math.Abs(pointA.X - pointB.X) 34 , Math.Abs(pointA.Y - pointB.Y)); 35 } 36 37 private Color GetRandomColor() 38 { 39 return Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); 40 } 41 42 private void ShowInformation(string message) 43 { 44 lblInformation.Text = message; 45 } 46 47 private void btnChangePenColor_Click(object sender, EventArgs e) 48 { 49 if (colors.ShowDialog(this) == DialogResult.OK) 50 { 51 penColor = colors.Color; 52 } 53 } 54 55 private void btnSwitchDoubleBuffered_Click(object sender, EventArgs e) 56 { 57 DoubleBuffered = !DoubleBuffered; 58 59 ShowInformation($"二級緩衝:{DoubleBuffered}。"); 60 } 61 62 private void btnDrawRandomRectangle_Click(object sender, EventArgs e) 63 { 64 var rectangle = GetRandomRectangle(); 65 66 var style = (DashStyle)(random.Next(0, 6)); 67 var dashCaps = new List<int> { 0, 2, 3 }; 68 var dashCap = (DashCap)dashCaps[random.Next(0, 3)]; 69 70 using (var g = CreateGraphics()) 71 using (var pen = new Pen(penColor, 4f)) 72 using (var brush = new LinearGradientBrush(rectangle, Color.Red, Color.Blue, LinearGradientMode.ForwardDiagonal)) 73 { 74 g.Clear(SystemColors.AppWorkspace); 75 g.SmoothingMode = SmoothingMode.HighQuality; 76 pen.DashStyle = style; 77 pen.DashCap = dashCap; 78 g.DrawRectangle(pen, rectangle); 79 } 80 81 ShowInformation($"隨機矩形,{rectangle},虛線冒:{dashCap.ToString()},線條樣式:{style.ToString()}。"); 82 } 83 84 …… 85 } 86 }
與上一節給出的窗體定義及輔助方法雷同,這裡不做過多說明,增加了兩個輔助方法,一個是獲取隨機矩形Rectangle GetRandomRectangle(),一個是獲取隨機顏色Color GetRandomColor(),相信什麼是矩形和顏色,生物老師都教過:)而且本節的重點也不在邊線的繪製上,其基本方法就是Graphics.DrawRectangle(Pen pen, Rectangle rect),也直接給出了繪製“隨機矩形”的程式碼,有了畫線的基礎,應該沒什麼問題了。
下面,重點來了:
1、繪製具有漸變色填充的矩形
1 private void btnFillLinearGradientColor_Click(object sender, EventArgs e) 2 { 3 var rectangle1 = GetRandomRectangle(); 4 var rectangle2 = GetRandomRectangle(); 5 6 var gradient = (LinearGradientMode)(random.Next(0, 4)); 7 var angle = (random.Next(0, 361)); 8 9 using (var g = CreateGraphics()) 10 { 11 g.Clear(SystemColors.AppWorkspace); 12 g.SmoothingMode = SmoothingMode.HighQuality; 13 using (var brush = new LinearGradientBrush(rectangle1, GetRandomColor(), GetRandomColor(), gradient)) 14 { 15 g.FillRectangle(brush, rectangle1); 16 } 17 18 using (var brush = new LinearGradientBrush(rectangle2, GetRandomColor(), GetRandomColor(), angle, 0 == angle % 2)) 19 { 20 g.FillRectangle(brush, rectangle2); 21 } 22 } 23 24 ShowInformation($"漸變色填充,{rectangle1},LinearGradient:{gradient};{rectangle2},Angle:{angle}。"); 25 }
繪製漸變色填充,關鍵在於構造一個合適的LinearGradientBrush,然後呼叫Graphics.FillRectangle(Brush brush, Rectangle rect)就可以了。
// // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.LinearGradientBrush // class with the specified points and colors. // // Parameters: // point1: // A System.Drawing.PointF structure that represents the starting point of the linear // gradient. // // point2: // A System.Drawing.PointF structure that represents the endpoint of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color of the linear // gradient. // // color2: // A System.Drawing.Color structure that represents the ending color of the linear // gradient. public LinearGradientBrush(PointF point1, PointF point2, Color color1, Color color2); // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.LinearGradientBrush // class with the specified points and colors. // // Parameters: // point1: // A System.Drawing.Point structure that represents the starting point of the linear // gradient. // // point2: // A System.Drawing.Point structure that represents the endpoint of the linear gradient. // // color1: // A System.Drawing.Color structure that represents the starting color of the linear // gradient. // // color2: // A System.Drawing.Color structure that represents the ending color of the linear // gradient. public LinearGradientBrush(Point point1, Point point2, Color color1, Color color2); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush based // on a rectangle, starting and ending colors, and an orientation mode. // // Parameters: // rect: // A System.Drawing.RectangleF structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // linearGradientMode: // A System.Drawing.Drawing2D.LinearGradientMode enumeration element that specifies // the orientation of the gradient. The orientation determines the starting and // ending points of the gradient. For example, LinearGradientMode.ForwardDiagonal // specifies that the starting point is the upper-left corner of the rectangle and // the ending point is the lower-right corner of the rectangle. public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode linearGradientMode); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush class // based on a rectangle, starting and ending colors, and orientation. // // Parameters: // rect: // A System.Drawing.Rectangle structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // linearGradientMode: // A System.Drawing.Drawing2D.LinearGradientMode enumeration element that specifies // the orientation of the gradient. The orientation determines the starting and // ending points of the gradient. For example, LinearGradientMode.ForwardDiagonal // specifies that the starting point is the upper-left corner of the rectangle and // the ending point is the lower-right corner of the rectangle. public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush class // based on a rectangle, starting and ending colors, and an orientation angle. // // Parameters: // rect: // A System.Drawing.RectangleF structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // angle: // The angle, measured in degrees clockwise from the x-axis, of the gradient's orientation // line. public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush class // based on a rectangle, starting and ending colors, and an orientation angle. // // Parameters: // rect: // A System.Drawing.Rectangle structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // angle: // The angle, measured in degrees clockwise from the x-axis, of the gradient's orientation // line. public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush class // based on a rectangle, starting and ending colors, and an orientation angle. // // Parameters: // rect: // A System.Drawing.RectangleF structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // angle: // The angle, measured in degrees clockwise from the x-axis, of the gradient's orientation // line. // // isAngleScaleable: // Set to true to specify that the angle is affected by the transform associated // with this System.Drawing.Drawing2D.LinearGradientBrush; otherwise, false. public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle, bool isAngleScaleable); // // Summary: // Creates a new instance of the System.Drawing.Drawing2D.LinearGradientBrush class // based on a rectangle, starting and ending colors, and an orientation angle. // // Parameters: // rect: // A System.Drawing.Rectangle structure that specifies the bounds of the linear // gradient. // // color1: // A System.Drawing.Color structure that represents the starting color for the gradient. // // color2: // A System.Drawing.Color structure that represents the ending color for the gradient. // // angle: // The angle, measured in degrees clockwise from the x-axis, of the gradient's orientation // line. // // isAngleScaleable: // Set to true to specify that the angle is affected by the transform associated // with this System.Drawing.Drawing2D.LinearGradientBrush; otherwise, false. public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable);
從LinearGradientBrush的一系列建構函式可以看出,LinearGradientBrush意在指出完成從一種顏色漸變到另一種顏色的漸變週期。
這裡我們著重說一下LinearGradientBrush的第一個引數,無論是一個Rectangle還是兩個Point,他們描述的是漸變色完成的區間。為了理解和描述上的方便,我們假設繪製的是一個水平方向的漸變,
這個時候,漸變區間與我們要填充的矩形並沒有交集,我們可以這樣理解,這個漸變區間會以定義的區域為原點,向四周擴散,
然後在填充的時候,只保留了我們要填充的矩形區域可見,
OK,假設我已經把這個關係說清楚了:)在有就是LinearGradientMode這個列舉,
// // Summary: // Specifies the direction of a linear gradient. public enum LinearGradientMode { // // Summary: // Specifies a gradient from left to right. Horizontal = 0, // // Summary: // Specifies a gradient from top to bottom. Vertical = 1, // // Summary: // Specifies a gradient from upper left to lower right. ForwardDiagonal = 2, // // Summary: // Specifies a gradient from upper right to lower left. BackwardDiagonal = 3 }System.Drawing.Drawing2D.LinearGradientMode
它列舉了從第一種顏色過渡到第二種顏色的方向,從左到右,從上到下,從左上到右下,從右上到左下四個比較正規的方向;
關於LinearGradientBrush的另一個引數(float angle),它用來指示顏色過渡的方向,結合LinearGradientMode理解,同時,指出,angle可以為負數,下圖幫助理解一下GDI+中的angle:
LinearGradientBrush類還有一些非常有用的屬性和方法,可以幫助完成一些更為複雜的任務,這裡就不細說了,又需要的童鞋可以深入研究一下:)
// // Summary: // Gets or sets a System.Drawing.Drawing2D.ColorBlend that defines a multicolor // linear gradient. // // Returns: // A System.Drawing.Drawing2D.ColorBlend that defines a multicolor linear gradient. public ColorBlend InterpolationColors { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.Blend that specifies positions and factors // that define a custom falloff for the gradient. // // Returns: // A System.Drawing.Drawing2D.Blend that represents a custom falloff for the gradient. public Blend Blend { get; set; } // // Summary: // Gets or sets a value indicating whether gamma correction is enabled for this // System.Drawing.Drawing2D.LinearGradientBrush. // // Returns: // The value is true if gamma correction is enabled for this System.Drawing.Drawing2D.LinearGradientBrush; // otherwise, false. public bool GammaCorrection { get; set; } // // Summary: // Gets a rectangular region that defines the starting and ending points of the // gradient. // // Returns: // A System.Drawing.RectangleF structure that specifies the starting and ending // points of the gradient. public RectangleF Rectangle { get; } // // Summary: // Gets or sets the starting and ending colors of the gradient. // // Returns: // An array of two System.Drawing.Color structures that represents the starting // and ending colors of the gradient. public Color[] LinearColors { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.WrapMode enumeration that indicates the // wrap mode for this System.Drawing.Drawing2D.LinearGradientBrush. // // Returns: // A System.Drawing.Drawing2D.WrapMode that specifies how fills drawn with this // System.Drawing.Drawing2D.LinearGradientBrush are tiled. public WrapMode WrapMode { get; set; } // // Summary: // Gets or sets a copy System.Drawing.Drawing2D.Matrix that defines a local geometric // transform for this System.Drawing.Drawing2D.LinearGradientBrush. // // Returns: // A copy of the System.Drawing.Drawing2D.Matrix that defines a geometric transform // that applies only to fills drawn with this System.Drawing.Drawing2D.LinearGradientBrush. public Matrix Transform { get; set; } // // Summary: // Creates an exact copy of this System.Drawing.Drawing2D.LinearGradientBrush. // // Returns: // The System.Drawing.Drawing2D.LinearGradientBrush this method creates, cast as // an object. public override object Clone(); // // Summary: // Multiplies the System.Drawing.Drawing2D.Matrix that represents the local geometric // transform of this System.Drawing.Drawing2D.LinearGradientBrush by the specified // System.Drawing.Drawing2D.Matrix in the specified order. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix by which to multiply the geometric transform. // // order: // A System.Drawing.Drawing2D.MatrixOrder that specifies in which order to multiply // the two matrices. public void MultiplyTransform(Matrix matrix, MatrixOrder order); // // Summary: // Multiplies the System.Drawing.Drawing2D.Matrix that represents the local geometric // transform of this System.Drawing.Drawing2D.LinearGradientBrush by the specified // System.Drawing.Drawing2D.Matrix by prepending the specified System.Drawing.Drawing2D.Matrix. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix by which to multiply the geometric transform. public void MultiplyTransform(Matrix matrix); // // Summary: // Resets the System.Drawing.Drawing2D.LinearGradientBrush.Transform property to // identity. public void ResetTransform(); // // Summary: // Rotates the local geometric transform by the specified amount. This method prepends // the rotation to the transform. // // Parameters: // angle: // The angle of rotation. public void RotateTransform(float angle); // // Summary: // Rotates the local geometric transform by the specified amount in the specified // order. // // Parameters: // angle: // The angle of rotation. // // order: // A System.Drawing.Drawing2D.MatrixOrder that specifies whether to append or prepend // the rotation matrix. public void RotateTransform(float angle, MatrixOrder order); // // Summary: // Scales the local geometric transform by the specified amounts. This method prepends // the scaling matrix to the transform. // // Parameters: // sx: // The amount by which to scale the transform in the x-axis direction. // // sy: // The amount by which to scale the transform in the y-axis direction. public void ScaleTransform(float sx, float sy); // // Summary: // Scales the local geometric transform by the specified amounts in the specified // order. // // Parameters: // sx: // The amount by which to scale the transform in the x-axis direction. // // sy: // The amount by which to scale the transform in the y-axis direction. // // order: // A System.Drawing.Drawing2D.MatrixOrder that specifies whether to append or prepend // the scaling matrix. public void ScaleTransform(float sx, float sy, MatrixOrder order); // // Summary: // Creates a linear gradient with a center color and a linear falloff to a single // color on both ends. // // Parameters: // focus: // A value from 0 through 1 that specifies the center of the gradient (the point // where the gradient is composed of only the ending color). // // scale: // A value from 0 through1 that specifies how fast the colors falloff from the starting // color to focus (ending color) public void SetBlendTriangularShape(float focus, float scale); // // Summary: // Creates a linear gradient with a center color and a linear falloff to a single // color on both ends. // // Parameters: // focus: // A value from 0 through 1 that specifies the center of the gradient (the point // where the gradient is composed of only the ending color). public void SetBlendTriangularShape(float focus); // // Summary: // Creates a gradient falloff based on a bell-shaped curve. // // Parameters: // focus: // A value from 0 through 1 that specifies the center of the gradient (the point // where the gradient is composed of only the ending color). // // scale: // A value from 0 through 1 that specifies how fast the colors falloff from the // focus. public void SetSigmaBellShape(float focus, float scale); // // Summary: // Creates a gradient falloff based on a bell-shaped curve. // // Parameters: // focus: // A value from 0 through 1 that specifies the center of the gradient (the point // where the starting color and ending color are blended equally). public void SetSigmaBellShape(float focus); // // Summary: // Translates the local geometric transform by the specified dimensions. This method // prepends the translation to the transform. // // Parameters: // dx: // The value of the translation in x. // // dy: // The value of the translation in y. public void TranslateTransform(float dx, float dy); // // Summary: // Translates the local geometric transform by the specified dimensions in the specified // order. // // Parameters: // dx: // The value of the translation in x. // // dy: // The value of the translation in y. // // order: // The order (prepend or append) in which to apply the translation. public void TranslateTransform(float dx, float dy, MatrixOrder order);System.Drawing.Drawing2D.LinearGradientBrush的屬性和方法
2、繪製系統畫刷填充矩形
1 private void btnFillWithSystemBrushes_Click(object sender, EventArgs e) 2 { 3 var rectangle = GetRandomRectangle(); 4 5 var systemBrushes = new List<Brush> { 6 SystemBrushes.GradientInactiveCaption , 7 SystemBrushes.Window , 8 SystemBrushes.ScrollBar , 9 SystemBrushes.MenuText , 10 SystemBrushes.MenuHighlight , 11 SystemBrushes.MenuBar , 12 SystemBrushes.Menu , 13 SystemBrushes.InfoText , 14 SystemBrushes.Info , 15 SystemBrushes.InactiveCaptionText , 16 SystemBrushes.InactiveBorder , 17 SystemBrushes.InactiveCaption , 18 SystemBrushes.HotTrack , 19 SystemBrushes.HighlightText , 20 SystemBrushes.Highlight , 21 SystemBrushes.GrayText , 22 SystemBrushes.WindowText , 23 SystemBrushes.GradientActiveCaption , 24 SystemBrushes.ActiveBorder , 25 SystemBrushes.ActiveCaption , 26 SystemBrushes.ActiveCaptionText , 27 SystemBrushes.AppWorkspace , 28 SystemBrushes.ButtonFace , 29 SystemBrushes.ButtonHighlight , 30 SystemBrushes.WindowFrame , 31 SystemBrushes.ButtonShadow , 32 SystemBrushes.ControlLightLight , 33 SystemBrushes.ControlLight , 34 SystemBrushes.ControlDark , 35 SystemBrushes.ControlDarkDark , 36 SystemBrushes.ControlText , 37 SystemBrushes.Desktop , 38 SystemBrushes.Control ,}; 39 40 var brush = systemBrushes[random.Next(0, systemBrushes.Count)]; 41 42 using (var g = CreateGraphics()) 43 { 44 g.Clear(SystemColors.AppWorkspace); 45 g.SmoothingMode = SmoothingMode.HighQuality; 46 g.FillRectangle(brush, rectangle); 47 } 48 49 ShowInformation($"畫刷填充,{rectangle},畫刷名稱:{(brush as SolidBrush)?.Color.Name}。"); 50 }畫刷填充 —— btnFillWithSystemBrushes_Click
本示例取用系統畫刷SystemBrushes來作為填充,其實就是Windows系統的一些畫刷配置,比如桌面背景色、按鈕顏色等。除非製作自定義控制元件或元件,否則,其它場景可能很少應用。不過,這個示例也同樣適用於SolidBrush,就是純色畫刷。沒什麼特表之處,一筆帶過吧。
3、繪製鑲嵌填充矩形
1 private void btnFillWithHatchBrush_Click(object sender, EventArgs e) 2 { 3 var rectangle = GetRandomRectangle(); 4 5 var style = (HatchStyle)(random.Next(0, 53)); 6 var foreColor = GetRandomColor(); 7 var backColor = GetRandomColor(); 8 9 using (var g = CreateGraphics()) 10 using (var brush = new HatchBrush(style, foreColor, backColor)) 11 { 12 g.Clear(SystemColors.AppWorkspace); 13 g.SmoothingMode = SmoothingMode.HighQuality; 14 g.FillRectangle(brush, rectangle); 15 } 16 17 ShowInformation($"鑲嵌填充,{rectangle},前景色:{foreColor},背景色:{backColor},填充樣式:{style.ToString()}。"); 18 }鑲嵌填充 —— btnFillWithHatchBrush_Click
System.Drawing.Drawing2D.HatchBrush是一個比較有意思的畫刷,它根據兩種顏色和不同的鑲嵌樣式,組合出各種不同的圖案,比較適合作為場景的背景,建議多玩兒玩兒。
技術上沒什麼特別點,主要是支援的樣式比較多,就不一一介紹了。
namespace System.Drawing.Drawing2D { // // Summary: // Specifies the different patterns available for System.Drawing.Drawing2D.HatchBrush // objects. public enum HatchStyle { // // Summary: // A pattern of horizontal lines. Horizontal = 0, // // Summary: // Specifies hatch style System.Drawing.Drawing2D.HatchStyle.Horizontal. Min = 0, // // Summary: // A pattern of vertical lines. Vertical = 1, // // Summary: // A pattern of lines on a diagonal from upper left to lower right. ForwardDiagonal = 2, // // Summary: // A pattern of lines on a diagonal from upper right to lower left. BackwardDiagonal = 3, // // Summary: // Specifies horizontal and vertical lines that cross. Cross = 4, // // Summary: // Specifies the hatch style System.Drawing.Drawing2D.HatchStyle.Cross. LargeGrid = 4, // // Summary: // Specifies hatch style System.Drawing.Drawing2D.HatchStyle.SolidDiamond. Max = 4, // // Summary: // A pattern of crisscross diagonal lines. DiagonalCross = 5, // // Summary: // Specifies a 5-percent hatch. The ratio of foreground color to background color // is 5:95. Percent05 = 6, // // Summary: // Specifies a 10-percent hatch. The ratio of foreground color to background color // is 10:90. Percent10 = 7, // // Summary: // Specifies a 20-percent hatch. The ratio of foreground color to background color // is 20:80. Percent20 = 8, // // Summary: // Specifies a 25-percent hatch. The ratio of foreground color to background color // is 25:75. Percent25 = 9, // // Summary: // Specifies a 30-percent hatch. The ratio of foreground color to background color // is 30:70. Percent30 = 10, // // Summary: // Specifies a 40-percent hatch. The ratio of foreground color to background color // is 40:60. Percent40 = 11, // // Summary: // Specifies a 50-percent hatch. The ratio of foreground color to background color // is 50:50. Percent50 = 12, // // Summary: // Specifies a 60-percent hatch. The ratio of foreground color to background color // is 60:40. Percent60 = 13, // // Summary: // Specifies a 70-percent hatch. The ratio of foreground color to background color // is 70:30. Percent70 = 14, // // Summary: // Specifies a 75-percent hatch. The ratio of foreground color to background color // is 75:25. Percent75 = 15, // // Summary: // Specifies a 80-percent hatch. The ratio of foreground color to background color // is 80:100. Percent80 = 16, // // Summary: // Specifies a 90-percent hatch. The ratio of foreground color to background color // is 90:10. Percent90 = 17, // // Summary: // Specifies diagonal lines that slant to the right from top points to bottom points // and are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.ForwardDiagonal, // but are not antialiased. LightDownwardDiagonal = 18, // // Summary: // Specifies diagonal lines that slant to the left from top points to bottom points // and are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.BackwardDiagonal, // but they are not antialiased. LightUpwardDiagonal = 19, // // Summary: // Specifies diagonal lines that slant to the right from top points to bottom points, // are spaced 50 percent closer together than, and are twice the width of System.Drawing.Drawing2D.HatchStyle.ForwardDiagonal. // This hatch pattern is not antialiased. DarkDownwardDiagonal = 20, // // Summary: // Specifies diagonal lines that slant to the left from top points to bottom points, // are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.BackwardDiagonal, // and are twice its width, but the lines are not antialiased. DarkUpwardDiagonal = 21, // // Summary: // Specifies diagonal lines that slant to the right from top points to bottom points, // have the same spacing as hatch style System.Drawing.Drawing2D.HatchStyle.ForwardDiagonal, // and are triple its width, but are not antialiased. WideDownwardDiagonal = 22, // // Summary: // Specifies diagonal lines that slant to the left from top points to bottom points, // have the same spacing as hatch style System.Drawing.Drawing2D.HatchStyle.BackwardDiagonal, // and are triple its width, but are not antialiased. WideUpwardDiagonal = 23, // // Summary: // Specifies vertical lines that are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.Vertical. LightVertical = 24, // // Summary: // Specifies horizontal lines that are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.Horizontal. LightHorizontal = 25, // // Summary: // Specifies vertical lines that are spaced 75 percent closer together than hatch // style System.Drawing.Drawing2D.HatchStyle.Vertical (or 25 percent closer together // than System.Drawing.Drawing2D.HatchStyle.LightVertical). NarrowVertical = 26, // // Summary: // Specifies horizontal lines that are spaced 75 percent closer together than hatch // style System.Drawing.Drawing2D.HatchStyle.Horizontal (or 25 percent closer together // than System.Drawing.Drawing2D.HatchStyle.LightHorizontal). NarrowHorizontal = 27, // // Summary: // Specifies vertical lines that are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.Vertical // and are twice its width. DarkVertical = 28, // // Summary: // Specifies horizontal lines that are spaced 50 percent closer together than System.Drawing.Drawing2D.HatchStyle.Horizontal // and are twice the width of System.Drawing.Drawing2D.HatchStyle.Horizontal. DarkHorizontal = 29, // // Summary: // Specifies dashed diagonal lines, that slant to the right from top points to bottom // points. DashedDownwardDiagonal = 30, // // Summary: // Specifies dashed diagonal lines, that slant to the left from top points to bottom // points. DashedUpwardDiagonal = 31, // // Summary: // Specifies dashed horizontal lines. DashedHorizontal = 32, // // Summary: // Specifies dashed vertical lines. DashedVertical = 33, // // Summary: // Specifies a hatch that has the appearance of confetti. SmallConfetti = 34, // // Summary: // Specifies a hatch that has the appearance of confetti, and is composed of larger // pieces than System.Drawing.Drawing2D.HatchStyle.SmallConfetti. LargeConfetti = 35, // // Summary: // Specifies horizontal lines that are composed of zigzags. ZigZag = 36, // // Summary: // Specifies horizontal lines that are composed of tildes. Wave = 37, // // Summary: // Specifies a hatch that has the appearance of layered bricks that slant to the // left from top points to bottom points. DiagonalBrick = 38, // // Summary: // Specifies a hatch that has the appearance of horizontally layered bricks. HorizontalBrick = 39, // // Summary: // Specifies a hatch that has the appearance of a woven material. Weave = 40, // // Summary: // Specifies a hatch that has the appearance of a plaid material. Plaid = 41, // // Summary: // Specifies a hatch that has the appearance of divots. Divot = 42, // // Summary: // Specifies horizontal and vertical lines, each of which is composed of dots, that // cross. DottedGrid = 43, // // Summary: // Specifies forward diagonal and backward diagonal lines, each of which is composed // of dots, that cross. DottedDiamond = 44, // // Summary: // Specifies a hatch that has the appearance of diagonally layered shingles that // slant to the right from top points to bottom points. Shingle = 45, // // Summary: // Specifies a hatch that has the appearance of a trellis. Trellis = 46, // // Summary: // Specifies a hatch that has the appearance of spheres laid adjacent to one another. Sphere = 47, // // Summary: // Specifies horizontal and vertical lines that cross and are spaced 50 percent // closer together than hatch style System.Drawing.Drawing2D.HatchStyle.Cross. SmallGrid = 48, // // Summary: // Specifies a hatch that has the appearance of a checkerboard. SmallCheckerBoard = 49, // // Summary: // Specifies a hatch that has the appearance of a checkerboard with squares that // are twice the size of System.Drawing.Drawing2D.HatchStyle.SmallCheckerBoard. LargeCheckerBoard = 50, // // Summary: // Specifies forward diagonal and backward diagonal lines that cross but are not // antialiased. OutlinedDiamond = 51, // // Summary: // Specifies a hatch that has the appearance of a checkerboard placed diagonally. SolidDiamond = 52 } }System.Drawing.Drawing2D.HatchStyle
4、繪製紋理填充矩形
1 private void btnFillWithTextureBrush_Click(object sender, EventArgs e) 2 { 3 var rectangle = GetRandomRectangle(); 4 5 var wrapMode = (WrapMode)(random.Next(0, 5)); 6 7 var image = Icon.ToBitmap(); 8 9 using (var g = CreateGraphics()) 10 using (var brush = new TextureBrush(image, wrapMode)) 11 { 12 g.Clear(SystemColors.AppWorkspace); 13 g.SmoothingMode = SmoothingMode.HighQuality; 14 g.FillRectangle(brush, rectangle); 15 } 16 17 ShowInformation($"紋理填充,{rectangle},WrapMode:{wrapMode}。"); 18 }紋理填充 —— btnFillWithTextureBrush_Click
紋理填充的關鍵在於對System.Drawing.TextureBrush這個畫刷以及System.Drawing.Drawing2D.WrapMode的使用,
namespace System.Drawing { // // Summary: // Each property of the System.Drawing.TextureBrush class is a System.Drawing.Brush // object that uses an image to fill the interior of a shape. This class cannot // be inherited. public sealed class TextureBrush : Brush { // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image. // // Parameters: // bitmap: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. public TextureBrush(Image bitmap); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image and wrap mode. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // wrapMode: // A System.Drawing.Drawing2D.WrapMode enumeration that specifies how this System.Drawing.TextureBrush // object is tiled. public TextureBrush(Image image, WrapMode wrapMode); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image and bounding rectangle. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // dstRect: // A System.Drawing.RectangleF structure that represents the bounding rectangle // for this System.Drawing.TextureBrush object. public TextureBrush(Image image, RectangleF dstRect); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image and bounding rectangle. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // dstRect: // A System.Drawing.Rectangle structure that represents the bounding rectangle for // this System.Drawing.TextureBrush object. public TextureBrush(Image image, Rectangle dstRect); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image, wrap mode, and bounding rectangle. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // wrapMode: // A System.Drawing.Drawing2D.WrapMode enumeration that specifies how this System.Drawing.TextureBrush // object is tiled. // // dstRect: // A System.Drawing.RectangleF structure that represents the bounding rectangle // for this System.Drawing.TextureBrush object. public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image, wrap mode, and bounding rectangle. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // wrapMode: // A System.Drawing.Drawing2D.WrapMode enumeration that specifies how this System.Drawing.TextureBrush // object is tiled. // // dstRect: // A System.Drawing.Rectangle structure that represents the bounding rectangle for // this System.Drawing.TextureBrush object. public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image, bounding rectangle, and image attributes. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // dstRect: // A System.Drawing.RectangleF structure that represents the bounding rectangle // for this System.Drawing.TextureBrush object. // // imageAttr: // An System.Drawing.Imaging.ImageAttributes object that contains additional information // about the image used by this System.Drawing.TextureBrush object. public TextureBrush(Image image, RectangleF dstRect, ImageAttributes imageAttr); // // Summary: // Initializes a new System.Drawing.TextureBrush object that uses the specified // image, bounding rectangle, and image attributes. // // Parameters: // image: // The System.Drawing.Image object with which this System.Drawing.TextureBrush object // fills interiors. // // dstRect: // A System.Drawing.Rectangle structure that represents the bounding rectangle for // this System.Drawing.TextureBrush object. // // imageAttr: // An System.Drawing.Imaging.ImageAttributes object that contains additional information // about the image used by this System.Drawing.TextureBrush object. public TextureBrush(Image image, Rectangle dstRect, ImageAttributes imageAttr); // // Summary: // Gets or sets a copy of the System.Drawing.Drawing2D.Matrix object that defines // a local geometric transformation for the image associated with this System.Drawing.TextureBrush // object. // // Returns: // A copy of the System.Drawing.Drawing2D.Matrix object that defines a geometric // transformation that applies only to fills drawn by using this System.Drawing.TextureBrush // object. public Matrix Transform { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.WrapMode enumeration that indicates the // wrap mode for this System.Drawing.TextureBrush object. // // Returns: // A System.Drawing.Drawing2D.WrapMode enumeration that specifies how fills drawn // by using this System.Drawing.Drawing2D.LinearGradientBrush object are tiled. public WrapMode WrapMode { get; set; } // // Summary: // Gets the System.Drawing.Image object associated with this System.Drawing.TextureBrush // object. // // Returns: // An System.Drawing.Image object that represents the image with which this System.Drawing.TextureBrush // object fills shapes. public Image Image { get; } // // Summary: // Creates an exact copy of this System.Drawing.TextureBrush object. // // Returns: // The System.Drawing.TextureBrush object this method creates, cast as an System.Object // object. public override object Clone(); // // Summary: // Multiplies the System.Drawing.Drawing2D.Matrix object that represents the local // geometric transformation of this System.Drawing.TextureBrush object by the specified // System.Drawing.Drawing2D.Matrix object in the specified order. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix object by which to multiply the geometric // transformation. // // order: // A System.Drawing.Drawing2D.MatrixOrder enumeration that specifies the order in // which to multiply the two matrices. public void MultiplyTransform(Matrix matrix, MatrixOrder order); // // Summary: // Multiplies the System.Drawing.Drawing2D.Matrix object that represents the local // geometric transformation of this System.Drawing.TextureBrush object by the specified // System.Drawing.Drawing2D.Matrix object by prepending the specified System.Drawing.Drawing2D.Matrix // object. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix object by which to multiply the geometric // transformation. public void MultiplyTransform(Matrix matrix); // // Summary: // Resets the Transform property of this System.Drawing.TextureBrush object to identity. public void ResetTransform(); // // Summary: // Rotates the local geometric transformation of this System.Drawing.TextureBrush // object by the specified amount. This method prepends the rotation to the transformation. // // Parameters: // angle: // The angle of rotation. public void RotateTransform(float angle); // // Summary: // Rotates the local geometric transformation of this System.Drawing.TextureBrush // object by the specified amount in the specified order. // // Parameters: // angle: // The angle of rotation. // // order: // A System.Drawing.Drawing2D.MatrixOrder enumeration that specifies whether to // append or prepend the rotation matrix. public void RotateTransform(float angle, MatrixOrder order); // // Summary: // Scales the local geometric transformation of this System.Drawing.TextureBrush // object by the specified amounts. This method prepends the scaling matrix to the // transformation. // // Parameters: // sx: // The amount by which to scale the transformation in the x direction. // // sy: // The amount by which to scale the transformation in the y direction. public void ScaleTransform(float sx, float sy); // // Summary: // Scales the local geometric transformation of this System.Drawing.TextureBrush // object by the specified amounts in the specified order. // // Parameters: // sx: // The amount by which to scale the transformation in the x direction. // // sy: // The amount by which to scale the transformation in the y direction. // // order: // A System.Drawing.Drawing2D.MatrixOrder enumeration that specifies whether to // append or prepend the scaling matrix. public void ScaleTransform(float sx, float sy, MatrixOrder order); // // Summary: // Translates the local geometric transformation of this System.Drawing.TextureBrush // object by the specified dimensions. This method prepends the translation to the // transformation. // // Parameters: // dx: // The dimension by which to translate the transformation in the x direction. // // dy: // The dimension by which to translate the transformation in the y direction. public void TranslateTransform(float dx, float dy); // // Summary: // Translates the local geometric transformation of this System.Drawing.TextureBrush // object by the specified dimensions in the specified order. // // Parameters: // dx: // The dimension by which to translate the transformation in the x direction. // // dy: // The dimension by which to translate the transformation in the y direction. // // order: // The order (prepend or append) in which to apply the translation. public void TranslateTransform(float dx, float dy, MatrixOrder order); } }System.Drawing.TextureBrush
namespace System.Drawing.Drawing2D { // // Summary: // Specifies how a texture or gradient is tiled when it is smaller than the area // being filled. public enum WrapMode { // // Summary: // Tiles the gradient or texture. Tile = 0, // // Summary: // Reverses the texture or gradient horizontally and then tiles the texture or gradient. TileFlipX = 1, // // Summary: // Reverses the texture or gradient vertically and then tiles the texture or gradient. TileFlipY = 2, // // Summary: // Reverses the texture or gradient horizontally and vertically and then tiles the // texture or gradient. TileFlipXY = 3, // // Summary: // The texture or gradient is not tiled. Clamp = 4 } }System.Drawing.Drawing2D.WrapMode
TextureBrush這個畫刷的主要成分是Image,由於我們還沒接觸Image,這裡就簡單實現一下使用範例,等以後對Image有足夠的瞭解,這個畫刷也就非常簡單了。本示例就簡單的將窗體的Icon作為Image使用了。
5、繪製路徑過渡填充矩形
1 private void btnFillWithPathGradientBrush_Click(object sender, EventArgs e) 2 { 3 var rectangle = GetRandomRectangle(); 4 5 var wrapMode = (WrapMode)(random.Next(0, 5)); 6 7 var points = new Point[] { GetRandomPoint(), GetRandomPoint(), GetRandomPoint(), GetRandomPoint(), GetRandomPoint() }; 8 9 using (var g = CreateGraphics()) 10 using (var pen = new Pen(penColor, 2f)) 11 using (var brush = new PathGradientBrush(points, wrapMode)) 12 { 13 g.Clear(SystemColors.AppWorkspace); 14 g.SmoothingMode = SmoothingMode.HighQuality; 15 g.DrawRectangle(pen, rectangle); 16 g.FillRectangle(brush, rectangle); 17 } 18 19 ShowInformation($"路徑填充,{rectangle},WrapMode:{wrapMode}。"); 20 }路徑填充 —— btnFillWithPathGradientBrush_Click
路徑過渡填充的關鍵在於對System.Drawing.Drawing2D.PathGradientBrush的使用以及與紋理填充一樣的WrapMode。
namespace System.Drawing.Drawing2D { // // Summary: // Encapsulates a System.Drawing.Brush object that fills the interior of a System.Drawing.Drawing2D.GraphicsPath // object with a gradient. This class cannot be inherited. public sealed class PathGradientBrush : Brush { // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.PathGradientBrush // class with the specified points. // // Parameters: // points: // An array of System.Drawing.PointF structures that represents the points that // make up the vertices of the path. public PathGradientBrush(PointF[] points); // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.PathGradientBrush // class with the specified points. // // Parameters: // points: // An array of System.Drawing.Point structures that represents the points that make // up the vertices of the path. public PathGradientBrush(Point[] points); // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.PathGradientBrush // class with the specified path. // // Parameters: // path: // The System.Drawing.Drawing2D.GraphicsPath that defines the area filled by this // System.Drawing.Drawing2D.PathGradientBrush. public PathGradientBrush(GraphicsPath path); // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.PathGradientBrush // class with the specified points and wrap mode. // // Parameters: // points: // An array of System.Drawing.PointF structures that represents the points that // make up the vertices of the path. // // wrapMode: // A System.Drawing.Drawing2D.WrapMode that specifies how fills drawn with this // System.Drawing.Drawing2D.PathGradientBrush are tiled. public PathGradientBrush(PointF[] points, WrapMode wrapMode); // // Summary: // Initializes a new instance of the System.Drawing.Drawing2D.PathGradientBrush // class with the specified points and wrap mode. // // Parameters: // points: // An array of System.Drawing.Point structures that represents the points that make // up the vertices of the path. // // wrapMode: // A System.Drawing.Drawing2D.WrapMode that specifies how fills drawn with this // System.Drawing.Drawing2D.PathGradientBrush are tiled. public PathGradientBrush(Point[] points, WrapMode wrapMode); // // Summary: // Gets or sets a copy of the System.Drawing.Drawing2D.Matrix that defines a local // geometric transform for this System.Drawing.Drawing2D.PathGradientBrush. // // Returns: // A copy of the System.Drawing.Drawing2D.Matrix that defines a geometric transform // that applies only to fills drawn with this System.Drawing.Drawing2D.PathGradientBrush. public Matrix Transform { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.ColorBlend that defines a multicolor // linear gradient. // // Returns: // A System.Drawing.Drawing2D.ColorBlend that defines a multicolor linear gradient. public ColorBlend InterpolationColors { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.Blend that specifies positions and factors // that define a custom falloff for the gradient. // // Returns: // A System.Drawing.Drawing2D.Blend that represents a custom falloff for the gradient. public Blend Blend { get; set; } // // Summary: // Gets a bounding rectangle for this System.Drawing.Drawing2D.PathGradientBrush. // // Returns: // A System.Drawing.RectangleF that represents a rectangular region that bounds // the path this System.Drawing.Drawing2D.PathGradientBrush fills. public RectangleF Rectangle { get; } // // Summary: // Gets or sets the center point of the path gradient. // // Returns: // A System.Drawing.PointF that represents the center point of the path gradient. public PointF CenterPoint { get; set; } // // Summary: // Gets or sets an array of colors that correspond to the points in the path this // System.Drawing.Drawing2D.PathGradientBrush fills. // // Returns: // An array of System.Drawing.Color structures that represents the colors associated // with each point in the path this System.Drawing.Drawing2D.PathGradientBrush fills. public Color[] SurroundColors { get; set; } // // Summary: // Gets or sets the color at the center of the path gradient. // // Returns: // A System.Drawing.Color that represents the color at the center of the path gradient. public Color CenterColor { get; set; } // // Summary: // Gets or sets the focus point for the gradient falloff. // // Returns: // A System.Drawing.PointF that represents the focus point for the gradient falloff. public PointF FocusScales { get; set; } // // Summary: // Gets or sets a System.Drawing.Drawing2D.WrapMode that indicates the wrap mode // for this System.Drawing.Drawing2D.PathGradientBrush. // // Returns: // A System.Drawing.Drawing2D.WrapMode that specifies how fills drawn with this // System.Drawing.Drawing2D.PathGradientBrush are tiled. public WrapMode WrapMode { get; set; } // // Summary: // Creates an exact copy of this System.Drawing.Drawing2D.PathGradientBrush. // // Returns: // The System.Drawing.Drawing2D.PathGradientBrush this method creates, cast as an // object. public override object Clone(); // // Summary: // Updates the brush's transformation matrix with the product of brush's transformation // matrix multiplied by another matrix. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix that will be multiplied by the brush's current // transformation matrix. public void MultiplyTransform(Matrix matrix); // // Summary: // Updates the brush's transformation matrix with the product of the brush's transformation // matrix multiplied by another matrix. // // Parameters: // matrix: // The System.Drawing.Drawing2D.Matrix that will be multiplied by the brush's current // transformation matrix. // // order: // A System.Drawing.Drawing2D.MatrixOrder that specifies in which order to multiply // the two matrices. public void MultiplyTransform(Matrix matrix, MatrixOrder order); // // Summary: // Resets the System.Drawing.Drawing2D.PathGradientBrush.Transform property to identity. public void ResetTransform(); // // Summary: // Rotates the local geometric transform by the specified amount. This method prepends // the rotation to the transform. // // Parameters: // angle: // The angle (extent) of rotation. public void RotateTransform(float angle); // // Summary: // Rotates the local geometric transform by the specified amount in the specified // order. // // Parameters: // angle: // The angle (extent) of rotation. // // order: // A System.Drawing.Drawing2D.MatrixOrder that specifies whether to append or prepend // the rotation matrix. public void RotateTransform(float angle, MatrixOrder order); // // Summary: // Scales the local geometric transform by the specified amounts. This method prepends // the scaling matrix to the transform. // // Parameters: // sx: // The transform scale factor in the x-axis direction. // // sy: // The transfo