private void CreateImage() { string code = GetRandomText(); Bitmap bitmap = new Bitmap(200, 50, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bitmap); Pen pen = new Pen(Color.Yellow); Rectangle rect = new Rectangle(0, 0, 200, 50); SolidBrush b = new SolidBrush(Color.Black); SolidBrush blue = new SolidBrush(Color.Blue); int counter = 0; g.DrawRectangle(pen, rect); g.FillRectangle(b, rect); for (int i = 0; i < code.Length; i++) { g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10)); counter += 20; } DrawRandomLines(g); bitmap.Save(Response.OutputStream, ImageFormat.Gif); g.Dispose(); bitmap.Dispose(); }
/// <summary> /// ����ͼƬ /// </summary> /// <param name="checkCode">�����</param> private void CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 11.5);//����������趨ͼƬ��� Bitmap image = new Bitmap(iwidth, 20);//����һ������ Graphics g = Graphics.FromImage(image);//�ڻ����϶����ͼ��ʵ�� Font f = new Font("Arial",10,FontStyle.Bold);//���壬��С����ʽ Brush b = new SolidBrush(Color.Black);//������ɫ //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(Color.White);//������ɫ g.DrawString(checkCode, f, b, 3, 3); Pen blackPen = new Pen(Color.Black, 0); Random rand = new Random(); /*����� for (int i = 0; i < 5; i++) { int y = rand.Next(image.Height); g.DrawLine(blackPen, 0, y, image.Width, y); } */ System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); }
private bool done = false; // true when game is over // initialize variables and thread for connecting to server private void TicTacToeClientForm_Load(object sender, EventArgs e) { board = new Square[3, 3]; // create 9 Square objects and place them on the board board[0, 0] = new Square(board0Panel, ' ', 0); board[0, 1] = new Square(board1Panel, ' ', 1); board[0, 2] = new Square(board2Panel, ' ', 2); board[1, 0] = new Square(board3Panel, ' ', 3); board[1, 1] = new Square(board4Panel, ' ', 4); board[1, 2] = new Square(board5Panel, ' ', 5); board[2, 0] = new Square(board6Panel, ' ', 6); board[2, 1] = new Square(board7Panel, ' ', 7); board[2, 2] = new Square(board8Panel, ' ', 8); // create a SolidBrush for writing on the Squares brush = new SolidBrush(Color.Black); // make connection to server and get the associated // network stream connection = new TcpClient("127.0.0.1", 50000); stream = connection.GetStream(); writer = new BinaryWriter(stream); reader = new BinaryReader(stream); // start a new thread for sending and receiving messages outputThread = new Thread(new ThreadStart(Run)); outputThread.Start(); } // end method TicTacToeClientForm_Load
/// <summary> /// 文字水印处理方法 /// </summary> /// <param name="path">图片路径(绝对路径)</param> /// <param name="size">字体大小</param> /// <param name="letter">水印文字</param> /// <param name="color">颜色</param> /// <param name="location">水印位置</param> public static string LetterWatermark(string path, int size, string letter, Color color, string location) { #region string kz_name = Path.GetExtension(path); if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg") { DateTime time = DateTime.Now; string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString(); Image img = Bitmap.FromFile(path); Graphics gs = Graphics.FromImage(img); ArrayList loca = GetLocation(location, img, size, letter.Length); Font font = new Font("宋体", size); Brush br = new SolidBrush(color); gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString())); gs.Dispose(); string newpath = Path.GetDirectoryName(path) + filename + kz_name; img.Save(newpath); img.Dispose(); File.Copy(newpath, path, true); if (File.Exists(newpath)) { File.Delete(newpath); } } return path; #endregion }
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (null == value) value = 0; int progressVal; if (value != null) progressVal = (int) value; else progressVal = 1; float percentage = ((float)progressVal / 100.0f); // Need to convert to float before division; otherwise C# returns int which is 0 for anything but 100%. Brush backColorBrush = new SolidBrush(cellStyle.BackColor); Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor); // Draws the cell grid base.Paint(g, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground)); if (percentage > 0.0) { // Draw the progress bar and the text g.FillRectangle(new SolidBrush(Color.FromArgb(163, 189, 242)), cellBounds.X + 2, cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width - 4)), cellBounds.Height - 4); g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 4); } else { // draw the text if (null != this.DataGridView.CurrentRow && this.DataGridView.CurrentRow.Index == rowIndex) g.DrawString(progressVal.ToString() + "%", cellStyle.Font, new SolidBrush(cellStyle.SelectionForeColor), cellBounds.X + 6, cellBounds.Y + 4); else g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 4); } }
protected override void OnPaint(PaintEventArgs pevent) { var g = pevent.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Parent.BackColor); Rectangle BGEllipse = new Rectangle(0, 0, 18, 18); EnabledCheckedColor = ColorTranslator.FromHtml(HexColor); SolidBrush BG = new SolidBrush(Enabled ? Checked ? EnabledCheckedColor : EnabledUnCheckedColor : DisabledColor); //RadioButton BG if (Checked) { g.FillEllipse(new SolidBrush(Color.FromArgb(Alpha, BG.Color)), BGEllipse); g.FillEllipse(new SolidBrush(Color.White), new Rectangle(2, 2, 14, 14)); } else { g.FillEllipse(BG, BGEllipse); g.FillEllipse(new SolidBrush(Color.White), new Rectangle(2, 2, 14, 14)); } g.FillEllipse(BG, new Rectangle(PointAnimationNum, PointAnimationNum, SizeAnimationNum, SizeAnimationNum)); //RadioButton Text g.DrawString(Text, font.Roboto_Medium10, new SolidBrush(Enabled ? EnabledStringColor : DisabledStringColor), 20, 0); }
private void ValidateCode( string VNum ) { Bitmap Img = null; Graphics g = null; MemoryStream ms = null; int gheight = VNum.Length * 10; Img = new Bitmap( gheight, 15 ); g = Graphics.FromImage( Img ); //背景颜色 g.Clear( Color.White ); //文字字体 Font f = new Font( "宋体", 10 ); //文字颜色 SolidBrush s = new SolidBrush( Color.Red ); g.DrawString( VNum, f, s, 3, 3 ); ms = new MemoryStream(); Img.Save( ms, ImageFormat.Jpeg ); Response.ClearContent(); Response.ContentType = "images/Jpeg"; Response.BinaryWrite( ms.ToArray() ); g.Dispose(); Img.Dispose(); Response.End(); }
public void AddWatermark(string filename, ImageFormat imageFormat, Stream outputStream, HttpContext ctx) { Image bitmap = Image.FromFile(filename); Font font = new Font("Arial", 13, FontStyle.Bold, GraphicsUnit.Pixel); Random rnd = new Random(); Color color = Color.FromArgb(200, rnd.Next(255), rnd.Next(255), rnd.Next(255)); //Adds a black watermark with a low alpha value (almost transparent). Point atPoint = new Point(bitmap.Width / 2 - 40, bitmap.Height / 2 - 7); //The pixel point to draw the watermark at (this example puts it at 100, 100 (x, y)). SolidBrush brush = new SolidBrush(color); string watermarkText = "voobrazi.by"; Graphics graphics; try { graphics = Graphics.FromImage(bitmap); } catch { Image temp = bitmap; bitmap = new Bitmap(bitmap.Width, bitmap.Height); graphics = Graphics.FromImage(bitmap); graphics.DrawImage(temp, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel); temp.Dispose(); } graphics.DrawString(watermarkText, font, brush, atPoint); graphics.Dispose(); bitmap.Save(outputStream, imageFormat); bitmap.Dispose(); }
public HexView() { // Setup drawing objects NormalFontBrush = new SolidBrush(Color.Black); NormalFont = new Font("Courier New", 10); vsAddr.ValueChanged += this.VsAddr_ValueChanged; }
protected override void Blockchange2(Player p, ushort x, ushort y, ushort z, byte type, byte extType) { RevertAndClearState(p, x, y, z); CatchPos cpos = (CatchPos)p.blockchangeObject; GetRealBlock(type, extType, p, ref cpos); DrawOp drawOp = null; Brush brush = null; switch (cpos.solid) { case SolidType.solid: drawOp = new CuboidDrawOp(); break; case SolidType.hollow: drawOp = new CuboidHollowsDrawOp(); break; case SolidType.walls: drawOp = new CuboidWallsDrawOp(); break; case SolidType.holes: drawOp = new CuboidHolesDrawOp(); break; case SolidType.wire: drawOp = new CuboidWireframeDrawOp(); break; case SolidType.random: drawOp = new CuboidDrawOp(); brush = new RandomBrush(cpos.type, cpos.extType); break; } if (brush == null) brush = new SolidBrush(cpos.type, cpos.extType); ushort x1 = Math.Min(cpos.x, x), x2 = Math.Max(cpos.x, x); ushort y1 = Math.Min(cpos.y, y), y2 = Math.Max(cpos.y, y); ushort z1 = Math.Min(cpos.z, z), z2 = Math.Max(cpos.z, z); if (!DrawOp.DoDrawOp(drawOp, brush, p, x1, y1, z1, x2, y2, z2)) return; if (p.staticCommands) p.Blockchange += new Player.BlockchangeEventHandler(Blockchange1); }
public override void DrawBg(System.Drawing.Graphics g, System.Drawing.Rectangle rect, System.Drawing.Drawing2D.SmoothingMode smooth) { using (SolidBrush backBrush = new SolidBrush(BgColor)) g.FillRectangle(backBrush, rect); g.SmoothingMode = smooth; }
protected override void Blockchange2(Player p, ushort x, ushort y, ushort z, byte type, byte extType) { RevertAndClearState(p, x, y, z); CatchPos cpos = (CatchPos)p.blockchangeObject; GetRealBlock(type, extType, p, ref cpos); DrawOp drawOp = null; Brush brush = new SolidBrush(cpos.type, cpos.extType); if (y != cpos.y) { Player.SendMessage(p, "The two edges of the pyramid must be on the same level"); return; } switch (cpos.solid) { case SolidType.solid: drawOp = new PyramidSolidDrawOp(); break; case SolidType.hollow: drawOp = new PyramidHollowDrawOp(); break; case SolidType.reverse: drawOp = new PyramidReverseDrawOp(); break; } ushort x1 = Math.Min(cpos.x, x), x2 = Math.Max(cpos.x, x); ushort y1 = Math.Min(cpos.y, y), y2 = Math.Max(cpos.y, y); ushort z1 = Math.Min(cpos.z, z), z2 = Math.Max(cpos.z, z); if (!DrawOp.DoDrawOp(drawOp, brush, p, x1, y1, z1, x2, y2, z2)) return; if (p.staticCommands) p.Blockchange += new Player.BlockchangeEventHandler(Blockchange1); }
public void createimage(string randnum) { int iwidth = randnum.Length * 13; Bitmap image = new Bitmap(iwidth, 23); Graphics g = Graphics.FromImage(image); g.Clear(Color.White); Color[] color = { Color.Green, Color.Red, Color.Black, Color.Blue, Color.Orange }; string[] font = { "宋体", "黑体", "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" }; Random rand = new Random(); for (int i = 0; i < 50; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1); } for (int i = 0; i < randnum.Length; i++) { int m = rand.Next(5); int n = rand.Next(6); Color c = color[m]; Font f = new Font(font[n], 10, System.Drawing.FontStyle.Bold); Brush b = new SolidBrush(color[m]); g.DrawString(randnum.Substring(i, 1), f, b, 3 + (i * 12), 0); } g.DrawRectangle(new Pen(Color.DarkGray, 0), 0, 0, image.Width - 1, image.Height - 1); image.Save(@"D:\Visual Studio 2013\WebSites\netsec\12.gif", System.Drawing.Imaging.ImageFormat.Gif); g.Dispose(); image.Dispose(); }
private void CreateImage() { Session["captcha.guid"] = Guid.NewGuid().ToString ("N"); string code = GetRandomText(); Bitmap bitmap = new Bitmap(WIDTH,HEIGHT,System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bitmap); Pen pen = new Pen(Color.DarkSlateGray); Rectangle rect = new Rectangle(0,0,WIDTH,HEIGHT); SolidBrush background = new SolidBrush(Color.AntiqueWhite); SolidBrush textcolor = new SolidBrush(Color.DarkSlateGray); int counter = 0; g.DrawRectangle(pen, rect); g.FillRectangle(background, rect); for (int i = 0; i < code.Length; i++) { g.DrawString(code[i].ToString(), new Font("Verdana", 10 + rand.Next(6, 14)), textcolor, new PointF(10 + counter, 10)); counter += 25; } DrawRandomLines(g); bitmap.Save(Response.OutputStream,ImageFormat.Gif); g.Dispose(); bitmap.Dispose(); }
private void createImage(string checkcode) { if(checkcode ==null||checkcode.Trim() ==string .Empty) return; Bitmap image = new Bitmap((int)Math.Ceiling(checkcode.Length * 13.1), 22); Graphics grahics = Graphics.FromImage(image); grahics.Clear(Color.White); Random random=new Random() ; for (int i = 0; i < 18; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image .Height ); grahics.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2); } Font font = new Font("Arial", 11, FontStyle.Bold); Brush brush = new SolidBrush(Color.Black); grahics.DrawString(checkcode ,font,brush ,3,3); for (int i = 0; i < 80; i++) { int width = random.Next(image.Width ); int heigth = random.Next(image.Height ); image.SetPixel(width ,heigth ,Color.Silver ); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType="image/Jpeg"; Response.BinaryWrite(ms.ToArray()); grahics.Dispose(); image.Dispose(); }
protected override void ApplyTextWatermark(ImageProcessingActionExecuteArgs args, Graphics g) { // Draw a filled rectangle int rectangleWidth = 14; using (Brush brush = new SolidBrush(Color.FromArgb(220, Color.Red))) { g.FillRectangle(brush, new Rectangle(args.Image.Size.Width - rectangleWidth, 0, rectangleWidth, args.Image.Size.Height)); } using (System.Drawing.Drawing2D.Matrix transform = g.Transform) { using (StringFormat stringFormat = new StringFormat()) { // Vertical text (bottom -> top) stringFormat.FormatFlags = StringFormatFlags.DirectionVertical; transform.RotateAt(180F, new PointF(args.Image.Size.Width / 2, args.Image.Size.Height / 2)); g.Transform = transform; // Align: top left, +2px displacement // (because of the matrix transformation we have to use inverted values) base.ContentAlignment = ContentAlignment.MiddleLeft; base.ContentDisplacement = new Point(-2, -2); base.ForeColor = Color.White; base.Font.Size = 10; // Draw the string by invoking the base Apply method base.StringFormat = stringFormat; base.ApplyTextWatermark(args, g); base.StringFormat = null; } } }
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { try { int progressVal = (int)value; float percentage = ((float)progressVal / 100.0f); // Need to convert to float before division; otherwise C# returns int which is 0 for anything but 100%. Brush backColorBrush = new SolidBrush(cellStyle.BackColor); Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor); // Draws the cell grid base.Paint(g, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground)); if (percentage > 0.0) { // Draw the progress bar and the text g.FillRectangle(new SolidBrush(Color.FromArgb(203, 235, 108)), cellBounds.X + 2, cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width - 4)), cellBounds.Height - 4); g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + (cellBounds.Width / 2) - 5, cellBounds.Y + 2); } else { g.DrawString("Ожидание...", cellStyle.Font, foreColorBrush, cellBounds.X + (cellBounds.Width / 2) - 25, cellBounds.Y + 2); } } catch (Exception e) { } }
public void OnRender(RenderTarget target) { if(gBorderBrush == null) { gBackgroundBrush = Brushes.Solid[0xCC555555]; gBackgroundHoverBrush = Brushes.Solid[0xCC888888]; gClickBrush = Brushes.Solid[0xFFFF7F00]; gBackgroundClickedBrush = Brushes.Solid[0xCCBBBBBB]; gBorderBrush = Brushes.White; } target.DrawTextLayout(new Vector2(Position.X + Size + 7, Position.Y - 2), mTextDraw, Brushes.White); var brush = gBackgroundBrush; if (mIsPressed) brush = gBackgroundClickedBrush; else if (mIsHovered) brush = gBackgroundHoverBrush; target.FillRectangle(mTargetRect, brush); target.DrawRectangle(mTargetRect, gBorderBrush); if (!Checked) return; target.DrawLine(Position + new Vector2(3, 3), Position + new Vector2(mSize - 3, mSize - 3), gClickBrush, mSize / 4.0f); target.DrawLine(new Vector2(Position.X + 3, Position.Y + mSize - 3), new Vector2(Position.X + mSize - 3, Position.Y + 3), gClickBrush, mSize / 4.0f); }
private void save() { //임의의 글자를 난수로 발생시켜 PrintStr에 집어넣기 string[] RandomStr = new string[] { "자동", "가입", "프로", "그램", "쓰지", "말자" }; Random r = new Random(); string PrintStr = RandomStr[r.Next(6)]; //랜덤으로 그리는 글씨를 ViewState에 저장한다.(나중에 검사할때 사용) ViewState["Str"] = PrintStr; //비트맵객체를 생성하고 이 객체를 Graphics객체에서 생성한다. Bitmap btm = new Bitmap(100, 80); Graphics grp = Graphics.FromImage(btm); //회색바탕의 사각형을 만들기 SolidBrush backBrush = new SolidBrush(Color.DarkGray); Rectangle rect = new Rectangle(0, 0, 100, 80);//100,80의 사이즈 grp.FillRectangle(backBrush, rect);//뒷 배경과 사각형 객체를 전달한다. //빨간색 글씨를 써서 집어넣는다. Font font = new Font("굴림", 20); SolidBrush strinBrush = new SolidBrush(Color.Red); grp.DrawString(PrintStr, font, strinBrush, 20, 20); //이제 만들어진 객체를 저장 시키자. string pathStr = MapPath(Request.ApplicationPath) + @"\img\Background.png"; btm.Save(pathStr, ImageFormat.Png); }
protected void Page_Load(object sender, EventArgs e) { string fName = ConfigurationManager.AppSettings["Code39Barcode.FontFamily"]; PrivateFontCollection fCollection = new PrivateFontCollection(); fCollection.AddFontFile(ConfigurationManager.AppSettings["Code39Barcode.FontFile"]); FontFamily fFamily = new FontFamily(fName, fCollection); Font f = new Font(fFamily, FontSize); Bitmap bmp = new Bitmap(Width, Height); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); Brush b = new SolidBrush(Color.Black); g.DrawString("*" + strPortfolioID + "*", f, b, 0, 0); //PNG format has no visible compression artifacts like JPEG or GIF, so use this format, but it needs you to copy the bitmap into a new bitmap inorder to display the image properly. Weird MS bug. Bitmap bm = new Bitmap(bmp); System.IO.MemoryStream ms = new System.IO.MemoryStream(); Response.ContentType = "image/png"; bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.WriteTo(Response.OutputStream); b.Dispose(); bm.Dispose(); Response.End(); }
protected void Page_Load(object sender, EventArgs e) { var fcaptcha = MapPath("~/Css/Login-Box/Captcha.bmp"); var bmpCaptcha = new Bitmap(fcaptcha); var g = Graphics.FromImage(bmpCaptcha); var code = RandomizeText(5); var gray = new SolidBrush(Color.DimGray); var rand = new Random(); var counter = 0; for (int i = 0; i < code.Length; i++) { g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(20)), gray, new PointF(40 + counter, 10)); counter += 20; } // Assign Code Session["Captcha"] = code; // Response Response.Clear(); Response.ContentType = "image/jpeg"; bmpCaptcha.Save(Response.OutputStream, ImageFormat.Jpeg); bmpCaptcha.Dispose(); g.Dispose(); Response.End(); }
protected override void OnPaint(PaintEventArgs pevent) { var g = pevent.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Parent.BackColor); var checkMarkLine = new Rectangle(1, 1, 16, 16); var checkmarkPath = DrawHelper.CreateRoundRect(1, 1, 17, 17, 1); EnabledCheckedColor = HexColor; SolidBrush BG = new SolidBrush(Enabled ? Checked ? EnabledCheckedColor : EnabledUnCheckedColor : DisabledColor); Pen Pen = new Pen(BG.Color); g.FillPath(BG, checkmarkPath); g.DrawPath(Pen, checkmarkPath); g.SmoothingMode = SmoothingMode.None; g.FillRectangle(new SolidBrush(Color.White), PointAnimationNum, PointAnimationNum, SizeAnimationNum, SizeAnimationNum); g.SmoothingMode = SmoothingMode.AntiAlias; //CheckMark g.DrawImageUnscaledAndClipped(CheckMarkBitmap(), checkMarkLine); //CheckBox Text g.DrawString(Text, font.Roboto_Medium10, new SolidBrush(Enabled ? EnabledStringColor : DisabledStringColor), 21, 0); }
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { try { Color bc = theme.BackColor; if (((ToolStripMenuItem)e.Item).Checked == true) { bc= theme.HoverColor; } else { bc = theme.BackColor; } e.Item.ForeColor = theme.ForeColor; e.ToolStrip.BackColor = theme.BackColor; Rectangle rc = new Rectangle(Point.Empty, e.Item.Size); Color c = (Color)(e.Item.Selected ? theme.HoverColor : bc); using (SolidBrush brush = new SolidBrush(c)) { e.Graphics.FillRectangle(brush, rc); } } catch (Exception ex) { } }
public static void Run() { // ExStart:AddWatermarkToImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages(); // Create an instance of Image and load an existing image using (Image image = Image.Load(dataDir + "WaterMark.bmp")) { // Create and initialize an instance of Graphics class Graphics graphics = new Graphics(image); // Creates an instance of Font Font font = new Font("Times New Roman", 16, FontStyle.Bold); // Create an instance of SolidBrush and set its various properties SolidBrush brush = new SolidBrush(); brush.Color = Color.Black; brush.Opacity = 100; // Draw a String using the SolidBrush object and Font, at specific Point and Save the image with changes. graphics.DrawString("Aspose.Imaging for .Net", font, brush, new PointF(image.Width / 2, image.Height / 2)); image.Save(dataDir + "AddWatermarkToImage_out.bmp"); // ExStart:AddWatermarkToImage // Display Status. Console.WriteLine("Watermark added successfully."); } }
protected override void OnDrawItem(DrawItemEventArgs e) { RectangleF tabFill = (RectangleF)GetTabRect(e.Index); if (e.Index == SelectedIndex) { Brush textBrush = new SolidBrush(Color.Black); Brush fillBrush = new SolidBrush(Color.White); e.Graphics.FillRectangle(fillBrush, tabFill); e.Graphics.DrawString(TabPages[e.Index].Text, Font, textBrush, new Point(e.Bounds.X + 5, e.Bounds.Y + 5)); int offset = (e.Bounds.Height - 16) / 2; e.Graphics.DrawImage(Image.FromFile(pathCloseImg), e.Bounds.X + e.Bounds.Width - 20, e.Bounds.Y + offset); textBrush.Dispose(); fillBrush.Dispose(); } else { Brush textBrush = new SolidBrush(Color.White); Brush fillBrush = new SolidBrush(Color.DimGray); e.Graphics.FillRectangle(fillBrush, tabFill); fillBrush.Dispose(); e.Graphics.DrawString(TabPages[e.Index].Text, Font, textBrush, new Point(e.Bounds.X + 5, e.Bounds.Y + 3)); int offset = (e.Bounds.Height - 16) / 2; e.Graphics.DrawImage(Image.FromFile(pathCloseImg), e.Bounds.X + e.Bounds.Width - 20, e.Bounds.Y + offset + 2); textBrush.Dispose(); fillBrush.Dispose(); } }
public override void Draw(System.Drawing.Graphics gr) { Brush brush = new SolidBrush(Color.Blue); PointF pos = GlobalPos; gr.FillEllipse(brush, pos.X - radius, pos.Y - radius, 2 * radius, 2 * radius); }
protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "image/bmp"; string st = "",s=""; Random rnd = new Random(); Int32 num=0,ch=0; for (int i = 0; i < 5; i++) { ch=rnd.Next(2); if (ch == 0) num = rnd.Next(65, 91); if (ch == 0) num = rnd.Next(97, 122); else num = rnd.Next(48, 57); s += (Convert.ToChar(num)).ToString(); st += (Convert.ToChar(num)).ToString() + " "; } Session.Add("captcha", s); Bitmap bmp = new Bitmap(210, 80); Graphics g = Graphics.FromImage(bmp); Pen p = new Pen(Color.Aqua); HatchBrush br = new HatchBrush(HatchStyle.DottedGrid, Color.Aqua, Color.LightGray); SolidBrush b = new SolidBrush(Color.Goldenrod); Font f = new Font("Chillar", 36); g.FillRectangle(br, new Rectangle(0, 0, 210, 80)); g.DrawString(st, f, b, new Point(5, 5)); bmp.Save(Response.OutputStream, ImageFormat.Bmp); g.DrawLine(p, 20, 10, 210, 80); }
internal void Draw(Graphics graphics) { if(!Visible) return; using(Brush brush=new SolidBrush(active ? ActiveColor : InactiveColor)) { graphics.FillEllipse(brush, 0,0, 2*radius, 2*radius); } }
private void DrawRandomLines(Graphics g) { SolidBrush green = new SolidBrush(Color.Green); //for (int i = 0; i < 20; i++) //{ // g.DrawLines(new Pen(green, 2), GetRandomPoints()); //} }
public static void CenterString(Graphics G, string T, Font F, Color C, Rectangle R) { SizeF TS = G.MeasureString(T, F); using (SolidBrush B = new SolidBrush(C)) { G.DrawString(T, F, B, new Point(R.Width / 2 - (((int)TS.Width) / 2), ((int)R.Height) / 2 - (((int)TS.Height) / 2))); } }
private void SystemWatcherControl_Paint(object sender, PaintEventArgs e) { int maximumHeight = GetTaskbarHeight(); if (maximumHeight <= 0) { maximumHeight = 30; } if (lastSize != maximumHeight) { this.Height = maximumHeight; lastSize = maximumHeight; } int graphPosition = 0; int graphPositionY = 0; System.Drawing.Graphics formGraphics = e.Graphics;// this.CreateGraphics(); foreach (var pair in Options.CounterOptions.Where(x => x.Value.Enabled == true)) { var name = pair.Key; var opt = pair.Value; var ct = Counters.Where(x => x.GetName() == name).Single(); var infos = ct.Infos; //var opt = Options.CounterOptions[ct.GetName()]; //if (!opt.Enabled) continue; var showCurrentValue = !opt.CurrentValueAsSummary && (opt.ShowCurrentValue == CounterOptions.DisplayType.SHOW || (opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER && mouseOver)); if (ct.GetCounterType() == TaskbarMonitor.Counters.ICounter.CounterType.SINGLE) { var info = infos[0]; drawGraph(formGraphics, graphPosition, 0 + graphPositionY, maximumHeight, false, info, defaultTheme, opt); } else if (ct.GetCounterType() == TaskbarMonitor.Counters.ICounter.CounterType.MIRRORED) { for (int z = 0; z < infos.Count; z++) { var info = opt.InvertOrder ? infos[infos.Count - 1 - z] : infos[z]; drawGraph(formGraphics, graphPosition, z * (maximumHeight / 2) + graphPositionY, maximumHeight / 2, z == 1, info, defaultTheme, opt); } } else if (ct.GetCounterType() == TaskbarMonitor.Counters.ICounter.CounterType.STACKED) { drawStackedGraph(formGraphics, graphPosition, 0 + graphPositionY, maximumHeight, opt.InvertOrder, infos, defaultTheme, opt); } var sizeTitle = formGraphics.MeasureString(ct.GetName(), fontTitle); Dictionary <CounterOptions.DisplayPosition, float> positions = new Dictionary <CounterOptions.DisplayPosition, float>(); positions.Add(CounterOptions.DisplayPosition.MIDDLE, (maximumHeight / 2 - sizeTitle.Height / 2) + 1 + graphPositionY); positions.Add(CounterOptions.DisplayPosition.TOP, graphPositionY); positions.Add(CounterOptions.DisplayPosition.BOTTOM, (maximumHeight - sizeTitle.Height + 1) + graphPositionY); CounterOptions.DisplayPosition?usedPosition = null; if (opt.ShowTitle == CounterOptions.DisplayType.SHOW || opt.ShowTitle == CounterOptions.DisplayType.HOVER) { usedPosition = opt.TitlePosition; var titleShadow = defaultTheme.TitleShadowColor; var titleColor = defaultTheme.TitleColor; if (opt.ShowTitle == CounterOptions.DisplayType.HOVER && !mouseOver) { titleColor = Color.FromArgb(40, titleColor.R, titleColor.G, titleColor.B); } System.Drawing.SolidBrush brushShadow = new System.Drawing.SolidBrush(titleShadow); System.Drawing.SolidBrush brushTitle = new System.Drawing.SolidBrush(titleColor); if ( (opt.ShowTitleShadowOnHover && opt.ShowTitle == CounterOptions.DisplayType.HOVER && !mouseOver) || (opt.ShowTitle == CounterOptions.DisplayType.HOVER && mouseOver) || opt.ShowTitle == CounterOptions.DisplayType.SHOW ) { if ((opt.ShowTitle == CounterOptions.DisplayType.HOVER && mouseOver) || opt.ShowTitle == CounterOptions.DisplayType.SHOW) { formGraphics.DrawString(ct.GetName(), fontTitle, brushShadow, new RectangleF(graphPosition + (Options.HistorySize / 2) - (sizeTitle.Width / 2) + 1, positions[opt.TitlePosition] + 1, sizeTitle.Width, maximumHeight), new StringFormat()); } formGraphics.DrawString(ct.GetName(), fontTitle, brushTitle, new RectangleF(graphPosition + (Options.HistorySize / 2) - (sizeTitle.Width / 2), positions[opt.TitlePosition], sizeTitle.Width, maximumHeight), new StringFormat()); } brushShadow.Dispose(); brushTitle.Dispose(); } if (opt.ShowCurrentValue == CounterOptions.DisplayType.SHOW || opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER) { Dictionary <CounterOptions.DisplayPosition, string> texts = new Dictionary <CounterOptions.DisplayPosition, string>(); if (opt.CurrentValueAsSummary || infos.Count > 2) { texts.Add(opt.SummaryPosition, ct.InfoSummary.CurrentStringValue); } else { List <CounterOptions.DisplayPosition> positionsAvailable = new List <CounterOptions.DisplayPosition> { CounterOptions.DisplayPosition.TOP, CounterOptions.DisplayPosition.MIDDLE, CounterOptions.DisplayPosition.BOTTOM }; if (usedPosition.HasValue) { positionsAvailable.Remove(usedPosition.Value); } var showName = infos.Count > 1; for (int i = 0; i < infos.Count && i < 2; i++) { texts.Add(positionsAvailable[i], (showName ? infos[i].Name + " " : "") + infos[i].CurrentStringValue); } } foreach (var item in texts) { string text = item.Value; var sizeString = formGraphics.MeasureString(text, fontCounter); float ypos = positions[item.Key]; var titleShadow = defaultTheme.TextShadowColor; var titleColor = defaultTheme.TextColor; if (opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER && !mouseOver) { titleColor = Color.FromArgb(40, titleColor.R, titleColor.G, titleColor.B); //titleShadow = Color.FromArgb(40, titleShadow.R, titleShadow.G, titleShadow.B); } SolidBrush BrushText = new SolidBrush(titleColor); SolidBrush BrushTextShadow = new SolidBrush(titleShadow); if ( (opt.ShowCurrentValueShadowOnHover && opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER && !mouseOver) || (opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER && mouseOver) || opt.ShowCurrentValue == CounterOptions.DisplayType.SHOW ) { if ((opt.ShowCurrentValue == CounterOptions.DisplayType.HOVER && mouseOver) || opt.ShowCurrentValue == CounterOptions.DisplayType.SHOW) { formGraphics.DrawString(text, fontCounter, BrushTextShadow, new RectangleF(graphPosition + (Options.HistorySize / 2) - (sizeString.Width / 2) + 1, ypos + 1, sizeString.Width, maximumHeight), new StringFormat()); } formGraphics.DrawString(text, fontCounter, BrushText, new RectangleF(graphPosition + (Options.HistorySize / 2) - (sizeString.Width / 2), ypos, sizeString.Width, maximumHeight), new StringFormat()); } BrushText.Dispose(); BrushTextShadow.Dispose(); } } graphPosition += Options.HistorySize + 10; if (graphPosition >= this.Size.Width) { graphPosition = 0; graphPositionY += (maximumHeight + 10); } } AdjustControlSize(); }
public override void OnMouseDown(int x, int y, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { n++; if (n == 1) { RGeos.Geometries.RgPoint pt = mScreenDisplay.DisplayTransformation.ToUnit(new PointF(x, y)); RGeos.Geometries.RgPoint P0 = new RGeos.Geometries.RgPoint(pt.X, pt.Y); RGeos.Geometries.RgPoint P1 = new RGeos.Geometries.RgPoint(pt.X, pt.Y); RGeos.Geometries.RgPoint P2 = new RGeos.Geometries.RgPoint(pt.X, pt.Y); vertices.Add(P0); vertices.Add(P1); vertices.Add(P2); line = new LinearRing(vertices); } else if (n == 2) { PointF p2 = new PointF(x, y); RGeos.Geometries.RgPoint pt1 = vertices[0]; RGeos.Geometries.RgPoint pt2 = mScreenDisplay.DisplayTransformation.ToUnit(p2); vertices[1] = pt2; mScreenDisplay.StartDrawing(mMapCtrl.CreateGraphics(), 1); mScreenDisplayDraw.DrawLine(pt1, pt2, Pens.Blue); mScreenDisplay.FinishDrawing(); //n = 0; } else if (n == 3) { PointF p1 = new PointF(x, y); RGeos.Geometries.RgPoint pt = mScreenDisplay.DisplayTransformation.ToUnit(p1); vertices[2] = pt; polygon.ExteriorRing = line; if (line != null) { SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(brush); mScreenDisplay.NewObject = polygon; mMapCtrl.Refresh(); } } else { PointF p1 = new PointF(x, y); RGeos.Geometries.RgPoint pt = mScreenDisplay.DisplayTransformation.ToUnit(p1); RGeos.Geometries.RgPoint P4 = pt; vertices.Add(P4); SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(brush); mScreenDisplay.NewObject = polygon; mMapCtrl.Refresh(); } } else if (e.Button == MouseButtons.Right) { Carto.FetureLayer featurelyr = mMapCtrl.Map.CurrentLayer as Carto.FetureLayer; if (featurelyr != null && featurelyr.ShapeType == RgEnumShapeType.RgPolygon) { featurelyr.AddFeature(polygon); } vertices = new List <RGeos.Geometries.RgPoint>(); polygon = new Polygon(); tempPolygon = new Polygon(); mScreenDisplay.NewObject = null; n = 0; mMapCtrl.Refresh(); } }
private void RedrawGraphicsA8B8G8R8(int width, int height, int pitch, int size) { // Use the whole area of the image to draw, even the alignment, otherwise it will shear the final image. int availableWidth = pitch / 4; int availableHeight = size / pitch; Debug.Assert(width <= availableWidth); Debug.Assert(height <= availableHeight); Debug.Assert(pitch * height <= size); _graphicsWidth = width; _graphicsHeight = height; _graphicsPitch = pitch; _graphicsSize = size; // WARNING: The color format is wrong because the system uses ABGR instead of ARGB, but // this is not a problem for black and white drawings. Bitmap bitmap = new Bitmap(availableWidth, availableHeight, PixelFormat.Format32bppArgb); using (var gfx = System.Drawing.Graphics.FromImage(bitmap)) { gfx.Clear(Color.Transparent); gfx.SmoothingMode = SmoothingMode.AntiAlias; gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.PixelOffsetMode = PixelOffsetMode.HighQuality; // The keyboard layer does not cover the entire visible area. const float keyboardHeightPercent = 0.625f; int keyboardHeight = (int)(keyboardHeightPercent * height); int keyboardTop = height - keyboardHeight; int keyboardWidth = width; int keyboardLeft = 0; RectangleF keyboardRectangle = new RectangleF(keyboardLeft, keyboardTop, keyboardWidth, keyboardHeight); // Fill the keyboard area with a transparent black color. SolidBrush backgroundBrush = new SolidBrush(Color.FromArgb(120, 0, 0, 0)); gfx.FillRectangle(backgroundBrush, keyboardRectangle); // Draw the first line larger then the second and third. System.Drawing.Font line1Font = new System.Drawing.Font("Tahoma", 40); System.Drawing.Font line2Font = new System.Drawing.Font("Tahoma", 20); System.Drawing.Font line3Font = line2Font; // Draw the first line in the center of the rectangle area, the second just below the first // and the third below the second. RectangleF line1Rectangle = keyboardRectangle; RectangleF line2Rectangle = line1Rectangle; RectangleF line3Rectangle = line1Rectangle; line2Rectangle.Y += 45; line3Rectangle.Y += 90; StringFormat stringFormat = new StringFormat(StringFormatFlags.NoClip); stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Alignment = StringAlignment.Center; gfx.DrawString(_line1Text, line1Font, Brushes.White, line1Rectangle, stringFormat); gfx.DrawString(_line2Text, line2Font, Brushes.White, line2Rectangle, stringFormat); gfx.DrawString(_line3Text, line3Font, Brushes.White, line3Rectangle, stringFormat); } Rectangle lockRectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData data = bitmap.LockBits(lockRectangle, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Debug.Assert(data.Stride == pitch); byte[] newGraphicsData = new byte[size]; Marshal.Copy(data.Scan0, newGraphicsData, 0, size); Volatile.Write(ref _graphicsData, newGraphicsData); }
public static Bitmap DesignerModeBitmap(Size size, bool drawArrows = false) { Bitmap bmp = new Bitmap(size.Width, size.Height); Graphics gfx = Graphics.FromImage(bmp); gfx.Clear(ColorTranslator.FromHtml("#003366")); Brush brushLogo = new SolidBrush(ColorTranslator.FromHtml("#FFFFFF")); Brush brushMeasurements = new SolidBrush(ColorTranslator.FromHtml("#006699")); Pen pen = new Pen(ColorTranslator.FromHtml("#006699"), 3); pen.StartCap = System.Drawing.Drawing2D.LineCap.Round; pen.EndCap = System.Drawing.Drawing2D.LineCap.Round; float arrowSize = 7; float padding = 3; // logo FontFamily ff = new FontFamily(Config.Fonts.GetDefaultFontName()); gfx.DrawString("ScottPlot", new Font(ff, 24, FontStyle.Bold), brushLogo, 10, 10); var titleSize = Drawing.GDI.MeasureString(gfx, "ScottPlot", new Font(ff, 24, FontStyle.Bold)); gfx.DrawString($"version {GetVersionString()}", new Font(ff, 12, FontStyle.Italic), brushLogo, 12, (int)(10 + titleSize.Height * .7)); if (drawArrows) { // horizontal arrow PointF left = new PointF(padding, size.Height / 2); PointF leftA = new PointF(left.X + arrowSize, left.Y + arrowSize); PointF leftB = new PointF(left.X + arrowSize, left.Y - arrowSize); PointF right = new PointF(size.Width - padding, size.Height / 2); PointF rightA = new PointF(right.X - arrowSize, right.Y + arrowSize); PointF rightB = new PointF(right.X - arrowSize, right.Y - arrowSize); gfx.DrawLine(pen, left, right); gfx.DrawLine(pen, left, leftA); gfx.DrawLine(pen, left, leftB); gfx.DrawLine(pen, right, rightA); gfx.DrawLine(pen, right, rightB); gfx.DrawString($"{size.Width}px", new Font(ff, 12, FontStyle.Bold), brushMeasurements, (float)(size.Width * .2), (float)(size.Height * .5)); // vertical arrow PointF top = new PointF(size.Width / 2, padding); PointF topA = new PointF(top.X - arrowSize, top.Y + arrowSize); PointF topB = new PointF(top.X + arrowSize, top.Y + arrowSize); PointF bot = new PointF(size.Width / 2, size.Height - padding); PointF botA = new PointF(bot.X - arrowSize, bot.Y - arrowSize); PointF botB = new PointF(bot.X + arrowSize, bot.Y - arrowSize); gfx.DrawLine(pen, top, bot); gfx.DrawLine(pen, bot, botA); gfx.DrawLine(pen, bot, botB); gfx.DrawLine(pen, top, topA); gfx.DrawLine(pen, top, topB); gfx.RotateTransform(-90); gfx.DrawString($"{size.Height}px", new Font(ff, 12, FontStyle.Bold), brushMeasurements, (float)(-size.Height * .4), (float)(size.Width * .5)); } return(bmp); }
private void panel1_Paint(object sender, PaintEventArgs e) { Panel panel = (Panel)sender; Graphics g = e.Graphics; Rectangle rect = new Rectangle(0, 0, panel.Width, panel.Height); g.FillRectangle(new SolidBrush(ReportViewUtils.perferBlue_Deep), rect); //起始坐标 int startX = 40; int startY = 40; //绘制宽高 int ArcWidth = 200; int ArcHeight = 5; //绘制的颜色 Color ArcColor = Color.FromArgb(255, 36, 169, 255); //字体颜色 Brush TextBrush = new SolidBrush(DrawUtils.ReportViewUtils.perferWhite_Shallow); //数据颜色 Brush DataBrush = new SolidBrush(Color.FromArgb(255, 253, 218, 4)); //绘制弧形矩阵报表 //utils.drawReportView(g, RePortViewStyle.Arc_angle_rectangle, startX, startY, ArcWidth, ArcHeight, ArcColor, TextBrush, DataBrush, "视频质量", 270, 300, "同步上升", 4, 8, 8); //ArcColor = ReportViewUtils.perferRed; //TextBrush = new SolidBrush(DrawUtils.ReportViewUtils.perferPurple); //DataBrush = new SolidBrush(Color.FromArgb(255, 253, 218, 4)); //utils.drawReportView(g, RePortViewStyle.Arc_angle_rectangle, startX, startY + 50, ArcWidth, ArcHeight, ArcColor, TextBrush, DataBrush, "录像", 130, 200); //utils.drawReportView(g, RePortViewStyle.Arc_angle_rectangle, 40, 150, 200, 5, ReportViewUtils.perferYellow, "完好率", 100, 400, 8, 8); //绘制弧形有事件触发矩阵报表 utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, startX, startY, ArcWidth, ArcHeight, ArcColor, TextBrush, DataBrush, "视频质量", 270, 300, "同步上升", 4, 8, 8); ArcColor = ReportViewUtils.perferRed; TextBrush = new SolidBrush(DrawUtils.ReportViewUtils.perferPurple); DataBrush = new SolidBrush(Color.FromArgb(255, 253, 218, 4)); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, startX, startY + 40, ArcWidth, ArcHeight, ArcColor, TextBrush, DataBrush, "录像", 130, 200); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, 40, startY + 80, 200, 5, ReportViewUtils.perferYellow, "完好率0", 100, 400, 8, 8); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, 40, startY + 120, 200, 5, ReportViewUtils.perferBlue, "完好率1", 100, 400, 8, 8); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, 40, startY + 160, 200, 5, ReportViewUtils.perferGreen, "完好率2", 100, 400, 8, 8); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, 40, startY + 200, 200, 5, ReportViewUtils.perferWhite, "完好率3", 100, 400, 8, 8); utils.drawReportView(g, RePortViewStyle.Arc_Angle_rectangle_EventHandle, 40, startY + 240, 200, 5, ReportViewUtils.perferPurple, "完好率4", 100, 400, 8, 8); //绘制多矩阵形式的报表 //ReportViewUtils.padding = 25; //utils.drawReportView(g, RePortViewStyle.MultiRectangle, 10, 20, 15, 30, ArcColor, "一致", 50, 100, 9, 15); //utils.drawReportView(g, RePortViewStyle.MultiRectangle, 10, 70, 15, 30, ReportViewUtils.perferRed, "错误", 60, 100, 9, 15); //utils.drawReportView(g, RePortViewStyle.MultiRectangle, 10, 120, 15, 30, ReportViewUtils.perferYellow, "未知", 764, 1000, 9, 15); //绘制弧形矩形报表 //ReportViewUtils.padding = 10; //utils.drawReportView(g, RePortViewStyle.Arc_rectangle, 10, 20, 100, 100, ArcColor, "平台接入", 150, 200, "同比下降", 4, 10, 16); //utils.drawReportView(g, RePortViewStyle.Arc_rectangle, 130, 20, 100, 100, ReportViewUtils.perferRed, "在线率", 100, 200, "同比下降", 4, 10, 16); //utils.drawReportView(g, RePortViewStyle.Arc_rectangle, 250, 20, 100, 100, ReportViewUtils.perferYellow, "故障点位", 180, 200, "同比上降", 4, 10, 16); ////绘制报表 //DataBean data = DataBeanFactory.CreateData(); //utils.DrawReportViewForCoordinate(g, ReportViewUtils.perferBlue, ReportViewUtils.perferWhite_Shallow, ReportViewUtils.perferPink, startX, startY, 500, 400, data); //DataBean data = DataBeanFactory.CreateTestData_02(); //utils.DrawReportViewForCoordinate(g, ReportViewUtils.perferBlue, ReportViewUtils.perferWhite_Shallow, ReportViewUtils.perferPink, startX, startY, 500, 400, data, 12, 8, 0, 0, true, false,false, false); //释放资源 utils.disposeGraphics(g); }
public abstract void draw(Graphics setPaint, SolidBrush shapeColor, int x, int y);
//===================================================================== // Methods, etc /// <summary> /// This is overridden to draw the text and the dividing line /// </summary> /// <param name="e">The event arguments</param> protected override void OnPaint(PaintEventArgs e) { Point pt, pt2; Rectangle r = base.ClientRectangle; SizeF size; Graphics g = e.Graphics; using (StringFormat sf = new StringFormat()) { sf.Trimming = StringTrimming.Character; sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Center; if (this.RightToLeft == RightToLeft.Yes) { sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } if (this.UseMnemonic) { sf.HotkeyPrefix = HotkeyPrefix.Show; } size = g.MeasureString(this.Text, this.Font, (SizeF)r.Size, sf); if (base.Enabled) { using (Brush fb = new SolidBrush(this.ForeColor)) { g.DrawString(this.Text, this.Font, fb, (RectangleF)r, sf); } } else { ControlPaint.DrawStringDisabled(g, this.Text, this.Font, this.BackColor, (RectangleF)r, sf); } pt = new Point(r.Left, r.Top + r.Height / 2); pt2 = new Point(r.Right, pt.Y); if (this.RightToLeft == RightToLeft.Yes) { pt2.X -= (int)size.Width; } else { pt.X += (int)size.Width; } using (Pen pb = new Pen(ControlPaint.Dark(this.BackColor), (float)SystemInformation.BorderSize.Height)) { if (base.FlatStyle == FlatStyle.Flat) { g.DrawLine(pb, pt, pt2); } else { using (Pen pf = new Pen( ControlPaint.LightLight(this.BackColor), (float)SystemInformation.BorderSize.Height)) { g.DrawLine(pb, pt, pt2); int offset = (int)Math.Ceiling((double) SystemInformation.BorderSize.Height / 2.0); pt.Offset(0, offset); pt2.Offset(0, offset); g.DrawLine(pf, pt, pt2); } } } } }
/// <summary> /// Forces a new CAPTCHA image to be generated using current property value settings. /// </summary> /// <returns>CAPTCHA image.</returns> public Bitmap GenerateImage() { Font font = null; Rectangle rectangle; Brush brush = null; Bitmap bitmap = null; Graphics graphics = null; GraphicsPath pathWithChar = null; StringFormat stringFormat = null; try { bitmap = new Bitmap(this.Width, this.Height, PixelFormat.Format32bppArgb); graphics = Graphics.FromImage(bitmap); graphics.SmoothingMode = SmoothingMode.AntiAlias; //// fill an empty white rectangle rectangle = new Rectangle(0, 0, this.Width, this.Height); brush = new SolidBrush(Color.White); graphics.FillRectangle(brush, rectangle); int charOffset = 0; double charWidth = this.Width / this.TextLength; Rectangle charRectangle; foreach (char c in this.Text.ToCharArray()) { //// establish font and draw area font = this.GetFont(); charRectangle = new Rectangle((int)(charOffset * charWidth), 0, (int)charWidth, this.Height); //// warp the character pathWithChar = new GraphicsPath(); stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Near; pathWithChar.AddString(c.ToString(), font.FontFamily, (int)font.Style, font.Size, charRectangle, stringFormat); this.WarpChar(pathWithChar, charRectangle); //// draw the character brush = new SolidBrush(Color.Black); graphics.FillPath(brush, pathWithChar); charOffset += 1; } this.AddNoise(graphics, rectangle); this.AddLines(graphics, rectangle); } finally { if (stringFormat != null) { stringFormat.Dispose(); } if (pathWithChar != null) { pathWithChar.Dispose(); } if (font != null) { font.Dispose(); } if (brush != null) { brush.Dispose(); } if (graphics != null) { graphics.Dispose(); } } return bitmap; }
public void DrawGraphs(Graphics graphics) { graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.High; graphics.ResetTransform(); graphics.ScaleTransform(_scale, _scale); graphics.TranslateTransform(_translatePoint.X, _translatePoint.Y); _matrixTransform = graphics.Transform; foreach (var graph in ListGraphs) { if (!IsShowGraph(graph)) { continue; } Brush textBrush = new SolidBrush(graph.TextConstructorColor); Font graphFont = new Font(FontFamily.GenericSansSerif, 12f, FontStyle.Bold); StringFormat textFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; Brush graphBrush = null; Pen graphPenBorder = new Pen(graph.GraphBorderColor, 1.0f); if (graph.IsCurrentGraphForResult) { graphBrush = new SolidBrush(graph.CurrentGraphResultColor); } else if (graph.IsPathForResult) { graphBrush = new SolidBrush(graph.GraphResultColor); } else { graphBrush = new SolidBrush(graph.GraphConstructorColor); } if (graph.IsReference) { PointF top = new PointF(graph.Rectangle.Left + graph.Rectangle.Width / 2.0f, graph.Rectangle.Top); PointF left = new PointF(graph.Rectangle.Left, graph.Rectangle.Bottom - graph.Rectangle.Height / 2.0f); PointF right = new PointF(graph.Rectangle.Right, graph.Rectangle.Bottom - graph.Rectangle.Height / 2.0f); PointF bottom = new PointF(graph.Rectangle.Left + graph.Rectangle.Width / 2.0f, graph.Rectangle.Bottom); graphics.FillPolygon(graphBrush, new[] { top, left, bottom, right }); } else if (graph.IsShowConsultation) { PointF top = new PointF(graph.Rectangle.Left + graph.Rectangle.Width / 2.0f, graph.Rectangle.Top); PointF left = new PointF(graph.Rectangle.Left, graph.Rectangle.Bottom); PointF right = new PointF(graph.Rectangle.Right, graph.Rectangle.Bottom); graphics.FillPolygon(graphBrush, new[] { top, left, right }); if (graph.IsDrawGraphBorderLine) { graphics.DrawPolygon(graphPenBorder, new[] { top, left, right }); } } else { graphics.FillRectangle(graphBrush, graph.Rectangle); if (graph.IsDrawGraphBorderLine) { graphics.DrawRectangle(graphPenBorder, graph.Rectangle.X, graph.Rectangle.Y, graph.Rectangle.Width, graph.Rectangle.Height); } } graphics.DrawString(graph.NameObject, graphFont, textBrush, graph.Rectangle, textFormat); if (!graph.IsReference) { DrawConnectionLine(graph, graphics); } graphBrush.Dispose(); graphBrush = null; textBrush.Dispose(); textBrush = null; graphFont.Dispose(); graphFont = null; } }
public void Draw(Graphics Gr) { SolidBrush brush = new SolidBrush(Color.Blue); Gr.FillRectangle(brush, new Rectangle(this.PosX, this.PosY, Width, Height)); }
/// <summary> /// Render this object to the specified <see cref="Graphics"/> device. /// </summary> /// <remarks> /// This method is normally only called by the Draw method /// of the parent <see cref="GraphObjList"/> collection object. /// </remarks> /// <param name="g"> /// A graphic device object to be drawn into. This is normally e.Graphics from the /// PaintEventArgs argument to the Paint() method. /// </param> /// <param name="pane"> /// A reference to the <see cref="PaneBase"/> object that is the parent or /// owner of this object. /// </param> /// <param name="scaleFactor"> /// The scaling factor to be used for rendering objects. This is calculated and /// passed down by the parent <see cref="GraphPane"/> object using the /// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust /// font sizes, etc. according to the actual size of the graph. /// </param> override public void Draw(Graphics g, PaneBase pane, float scaleFactor) { // Convert the arrow coordinates from the user coordinate system // to the screen coordinate system PointF pix1 = this.Location.TransformTopLeft(pane); PointF pix2 = this.Location.TransformBottomRight(pane); if (pix1.X > -10000 && pix1.X < 100000 && pix1.Y > -100000 && pix1.Y < 100000 && pix2.X > -10000 && pix2.X < 100000 && pix2.Y > -100000 && pix2.Y < 100000) { // get a scaled size for the arrowhead float scaledSize = (float)(_size * scaleFactor); // calculate the length and the angle of the arrow "vector" double dy = pix2.Y - pix1.Y; double dx = pix2.X - pix1.X; float angle = (float)Math.Atan2(dy, dx) * 180.0F / (float)Math.PI; float length = (float)Math.Sqrt(dx * dx + dy * dy); // Save the old transform matrix Matrix transform = g.Transform; // Move the coordinate system so it is located at the starting point // of this arrow g.TranslateTransform(pix1.X, pix1.Y); // Rotate the coordinate system according to the angle of this arrow // about the starting point g.RotateTransform(angle); // get a pen according to this arrow properties using (Pen pen = _line.GetPen(pane, scaleFactor)) //new Pen( _color, pane.ScaledPenWidth( _penWidth, scaleFactor ) ) ) { //pen.DashStyle = _style; // Only show the arrowhead if required if (_isArrowHead) { // Draw the line segment for this arrow g.DrawLine(pen, 0, 0, length - scaledSize + 1, 0); // Create a polygon representing the arrowhead based on the scaled // size PointF[] polyPt = new PointF[4]; float hsize = scaledSize / 3.0F; polyPt[0].X = length; polyPt[0].Y = 0; polyPt[1].X = length - scaledSize; polyPt[1].Y = hsize; polyPt[2].X = length - scaledSize; polyPt[2].Y = -hsize; polyPt[3] = polyPt[0]; using (SolidBrush brush = new SolidBrush(_line._color)) // render the arrowhead g.FillPolygon(brush, polyPt); } else { g.DrawLine(pen, 0, 0, length, 0); } } // Restore the transform matrix back to its original state g.Transform = transform; } }
/// <summary> /// Serialization constructor /// </summary> /// <param name="info"></param> /// <param name="context"></param> public SolidBrushRef(SerializationInfo info, StreamingContext context) { _brush = new SolidBrush((Color)info.GetValue("Color", typeof(Color))); }
public override void OnMouseMove(int x, int y) { if (n == 1) { } if (n == 2) { j++; tmpVertices = new List <RGeos.Geometries.RgPoint>(); RGeos.Geometries.RgPoint P0 = vertices[0]; RGeos.Geometries.RgPoint P1 = vertices[1]; RGeos.Geometries.RgPoint pt = mScreenDisplay.DisplayTransformation.ToUnit(new PointF(x, y)); RGeos.Geometries.RgPoint P2 = pt; tmpVertices.Add(P0); tmpVertices.Add(P1); tmpVertices.Add(P2); LinearRing tmpLine = new LinearRing(tmpVertices); tempPolygon.ExteriorRing = tmpLine; if (j == 1) { BoundingBox box = tempPolygon.GetBoundingBox(); PointF lowLeft = mScreenDisplay.DisplayTransformation.ToScreen(box.TopLeft); PointF topRight = mScreenDisplay.DisplayTransformation.ToScreen(box.BottomRight); double xmin = lowLeft.X; double ymin = lowLeft.Y; double w = Math.Abs(topRight.X - lowLeft.X); double h = Math.Abs(topRight.Y - lowLeft.Y); Rectangle invalidaterect = new Rectangle((int)xmin, (int)ymin, (int)w, (int)h); invalidaterect.Inflate(2, 2); (mScreenDisplay as ScreenDisplay).RepaintStatic(invalidaterect); j = 0; } SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(brush); mScreenDisplay.StartDrawing(mMapCtrl.CreateGraphics(), 1); mScreenDisplayDraw.DrawPolygon(tempPolygon, brush, pen, false); mScreenDisplay.FinishDrawing(); } else if (n > 2) { BoundingBox box = tempPolygon.GetBoundingBox(); PointF lowLeft = mScreenDisplay.DisplayTransformation.ToScreen(box.TopLeft); PointF topRight = mScreenDisplay.DisplayTransformation.ToScreen(box.BottomRight); double xmin = lowLeft.X; double ymin = lowLeft.Y; double w = Math.Abs(topRight.X - lowLeft.X); double h = Math.Abs(topRight.Y - lowLeft.Y); Rectangle invalidaterect = new Rectangle((int)xmin, (int)ymin, (int)w, (int)h); invalidaterect.Inflate(2, 2); (mScreenDisplay as ScreenDisplay).RepaintStatic(invalidaterect); tmpVertices = new List <RGeos.Geometries.RgPoint>(); RGeos.Geometries.RgPoint P0 = vertices[0]; RGeos.Geometries.RgPoint P1 = vertices[n - 1]; RGeos.Geometries.RgPoint pt = mScreenDisplay.DisplayTransformation.ToUnit(new PointF(x, y)); RGeos.Geometries.RgPoint P2 = pt; tmpVertices.Add(P0); tmpVertices.Add(P1); tmpVertices.Add(P2); LinearRing tmpLine = new LinearRing(tmpVertices); tempPolygon.ExteriorRing = tmpLine; SolidBrush brush = new SolidBrush(Color.Blue); SolidBrush brush2 = new SolidBrush(Color.Pink); Pen pen = new Pen(brush2); mScreenDisplay.StartDrawing(mMapCtrl.CreateGraphics(), 1); mScreenDisplayDraw.DrawPolygon(tempPolygon, brush, pen, false); mScreenDisplay.FinishDrawing(); } }
//cell painting的方式不好,不能居中而且不能选中合并后的单元格 private void dataGridViewX1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { foreach (string fieldHeaderText in colsHeaderText_H) { //纵向合并 if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].HeaderText == fieldHeaderText && e.RowIndex >= 0) { using ( Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor)) { using (Pen gridLinePen = new Pen(gridBrush)) { // 擦除原单元格背景 e.Graphics.FillRectangle(backColorBrush, e.CellBounds); /****** 绘制单元格相互间隔的区分线条,datagridview自己会处理左侧和上边缘的线条,因此只需绘制下边框和和右边框 DataGridView控件绘制单元格时,不绘制左边框和上边框,共用左单元格的右边框,上一单元格的下边框*****/ //不是最后一行且单元格的值不为null if (e.RowIndex < this.dataGridView1.RowCount - 1 && this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value != null) { //若与下一单元格值不同 if (e.Value.ToString() != this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString()) { //下边缘的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); //绘制值 if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } //若与下一单元格值相同 else { //背景颜色 //e.CellStyle.BackColor = Color.LightPink; //仅在CellFormatting方法中可用 this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue; this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue; //只读(以免双击单元格时显示值) this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true; this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].ReadOnly = true; } } //最后一行或单元格的值为null else { //下边缘的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); //绘制值 if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } ////左侧的线() //e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, // e.CellBounds.Top, e.CellBounds.Left, // e.CellBounds.Bottom - 1); //右侧的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); //设置处理事件完成(关键点),只有设置为ture,才能显示出想要的结果。 e.Handled = true; } } } } foreach (string fieldHeaderText in colsHeaderText_V) { //横向合并 if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].HeaderText == fieldHeaderText && e.RowIndex >= 0) { using ( Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor)) { using (Pen gridLinePen = new Pen(gridBrush)) { // 擦除原单元格背景 e.Graphics.FillRectangle(backColorBrush, e.CellBounds); /****** 绘制单元格相互间隔的区分线条,datagridview自己会处理左侧和上边缘的线条,因此只需绘制下边框和和右边框 DataGridView控件绘制单元格时,不绘制左边框和上边框,共用左单元格的右边框,上一单元格的下边框*****/ //不是最后一列且单元格的值不为null if (e.ColumnIndex < this.dataGridView1.ColumnCount - 1 && this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value != null) { if (e.Value.ToString() != this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value.ToString()) { //右侧的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); //绘制值 if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } //若与下一单元格值相同 else { //背景颜色 //e.CellStyle.BackColor = Color.LightPink; //仅在CellFormatting方法中可用 this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightPink; this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Style.BackColor = Color.LightPink; //只读(以免双击单元格时显示值) this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true; this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].ReadOnly = true; } } else { //右侧的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); //绘制值 if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } //下边缘的线 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); e.Handled = true; } } } } }
/// <summary> /// 打印事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { try { int y = 0; int rowGap = 30; int colGap = 30; int x = 1; Font captionFont = new Font("宋体", 18, FontStyle.Bold); Brush brush = new SolidBrush(Color.Black); for (int i = 0; i < lvwUserList.SelectedRows.Count; i++) { if (count != 0 && i == 0) { i = count + 1; } #region 杨敦钦 填充打印内容 和打印 e.Graphics.DrawString("重庆理文造纸有限公司国废质检抽包", captionFont, brush, rowGap, y, StringFormat.GenericDefault); int id = Convert.ToInt32(lvwUserList.SelectedRows[i].Cells["DRAW_EXAM_INTERFACE_ID"].Value); string prtSql = "select CNTR_NO,WEIGHT_TICKET_NO,PROD_ID,DRAW_ONE,DRAW_TWO,DRAW_THREE,DRAW_FOUR,DRAW_FIVE,DRAW_SIX,DRAW_7,DRAW_8,DRAW_9,DRAW_10,DRAW_11,DRAW_12,DRAW_13,DRAW_14 from dbo.DRAW_EXAM_INTERFACE where DRAW_EXAM_INTERFACE_ID=" + id; DataTable dtprt = LinQBaseDao.Query(prtSql).Tables[0]; if (dtprt.Rows.Count > 0) { y += colGap; //换行 string strattent = dtprt.Rows[0]["CNTR_NO"].ToString(); e.Graphics.DrawString("车牌号:" + strattent, captionFont, brush, rowGap, y, StringFormat.GenericDefault); //添加打印内容 strattent = dtprt.Rows[0]["WEIGHT_TICKET_NO"].ToString(); e.Graphics.DrawString("磅单号:" + strattent, captionFont, brush, 280, y, StringFormat.GenericDefault); //添加打印内容 strattent = dtprt.Rows[0]["PROD_ID"].ToString(); e.Graphics.DrawString("货品:" + strattent, captionFont, brush, 540, y, StringFormat.GenericDefault); //添加打印内容 y += colGap; //换行 strattent = ""; string ziduan = "DRAW_ONE,DRAW_TWO,DRAW_THREE,DRAW_FOUR,DRAW_FIVE,DRAW_SIX,DRAW_7,DRAW_8,DRAW_9,DRAW_10,DRAW_11,DRAW_12,DRAW_13,DRAW_14"; string[] danziduan = ziduan.Split(','); for (int j = 0; j < danziduan.Length; j++) { strattent = hbbh(dtprt, strattent, danziduan[j]); } if (strattent != "") { strattent = strattent.Substring(0, strattent.Length - 1); } e.Graphics.DrawString("包号:" + strattent, captionFont, brush, rowGap, y, StringFormat.GenericDefault);//添加打印内容 y += 50; } if (x >= 10) { e.HasMorePages = true;//分页 x = 1; count = i; if (i == lvwUserList.SelectedRows.Count - 1) { e.HasMorePages = false;//打印 } break; } if (i == lvwUserList.SelectedRows.Count - 1) { e.HasMorePages = false;//打印 } x++; #endregion } } catch { } }
///<summary>绘制合并表头 /// ///</summary> ///<param name="node">合并表头节点</param> ///<param name="e">绘图参数集</param> ///<param name="level">结点深度</param> ///<remarks></remarks> public void PaintUnitHeader( TreeNode node, System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int level) { //根节点时退出递归调用 if (level == 0) { return; } RectangleF uhRectangle; int uhWidth; SolidBrush gridBrush = new SolidBrush(this.GridColor); SolidBrush backColorBrush = new SolidBrush(e.CellStyle.BackColor); Pen gridLinePen = new Pen(gridBrush); StringFormat textFormat = new StringFormat(); textFormat.Alignment = StringAlignment.Center; uhWidth = GetUnitHeaderWidth(node); //与原贴算法有所区别在这。 if (node.Nodes.Count == 0) { uhRectangle = new Rectangle(e.CellBounds.Left, e.CellBounds.Top + node.Level * iCellHeight, uhWidth - 1, iCellHeight * (iNodeLevels - node.Level) - 1); } else { uhRectangle = new Rectangle( e.CellBounds.Left, e.CellBounds.Top + node.Level * iCellHeight, uhWidth - 1, iCellHeight - 1); } //画矩形 e.Graphics.FillRectangle(backColorBrush, uhRectangle); //划底线 e.Graphics.DrawLine(gridLinePen , uhRectangle.Left , uhRectangle.Bottom , uhRectangle.Right , uhRectangle.Bottom); //划右端线 e.Graphics.DrawLine(gridLinePen , uhRectangle.Right , uhRectangle.Top , uhRectangle.Right , uhRectangle.Bottom); e.Graphics.DrawString(node.Text, this.ColumnHeadersDefaultCellStyle.Font , Brushes.Black , uhRectangle.Left + uhRectangle.Width / 2 - e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Width / 2 - 1 , uhRectangle.Top + uhRectangle.Height / 2 - e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Height / 2); //递归调用() if (node.PrevNode == null) { if (node.Parent != null) { PaintUnitHeader(node.Parent, e, level - 1); } } }
/* * This is the thread that controls the build process * it needs to read the lines of gcode, one by one * send them to the printer interface, * wait for the printer to respond, * and also wait for the layer interval timer */ void BuildThread() { int now = Environment.TickCount; int nextlayertime = 0; while (m_running) { Thread.Sleep(0); // moved this sleep here for if the switch (m_state) { case BuildManager.STATE_START: //start things off, reset some variables RaiseStatusEvent(eBuildStatus.eBuildStarted, "Build Started"); m_state = BuildManager.STATE_DO_NEXT_LAYER; // go to the first layer m_gcodeline = 0; // set the start line m_curlayer = 0; m_printstarttime = new DateTime(); break; case BuildManager.STATE_WAITING_FOR_LAYER: //check time var if (Environment.TickCount >= nextlayertime) { m_state = BuildManager.STATE_DO_NEXT_LAYER; // move onto next layer } break; case BuildManager.STATE_IDLE: // do nothing break; case BuildManager.STATE_DO_NEXT_LAYER: //check for done if (m_gcodeline >= m_gcode.Lines.Length) { //we're done.. m_state = BuildManager.STATE_DONE; continue; } string line = ""; if (UVDLPApp.Instance().m_deviceinterface.ReadyForCommand()) { // go through the gcode, line by line line = m_gcode.Lines[m_gcodeline++]; } else { continue; // device is not ready } line = line.Trim(); if (line.Length > 0) // if the line is not blank { // send the line, whether or not it's a comment // should check to see if the firmware is ready for another line UVDLPApp.Instance().m_deviceinterface.SendCommandToDevice(line + "\r\n"); // if the line is a comment, parse it to see if we need to take action if (line.Contains("<Delay> ")) // get the delay { nextlayertime = Environment.TickCount + getvarfromline(line); m_state = STATE_WAITING_FOR_LAYER; continue; } else if (line.Contains("<Slice> ")) //get the slice number { int layer = getvarfromline(line); int curtype = BuildManager.SLICE_NORMAL; // assume it's a normal image to begin with Bitmap bmp = null; if (layer == SLICE_BLANK) { if (m_blankimage == null) // blank image is null, create it { m_blankimage = new Bitmap(m_sf.XProjRes, m_sf.YProjRes); // fill it with black using (Graphics gfx = Graphics.FromImage(m_blankimage)) using (SolidBrush brush = new SolidBrush(Color.Black)) { gfx.FillRectangle(brush, 0, 0, m_sf.XProjRes, m_sf.YProjRes); } } bmp = m_blankimage; curtype = BuildManager.SLICE_BLANK; } else { m_curlayer = layer; bmp = m_sf.GetSliceImage(m_curlayer); // get the rendered image slice or load it if already rendered } //raise a delegate so the main form can catch it and display layer information. if (PrintLayer != null) { PrintLayer(bmp, m_curlayer, curtype); } } } break; case BuildManager.STATE_DONE: m_running = false; m_state = BuildManager.STATE_IDLE; StopBuildTimer(); DateTime endtime = new DateTime(); double totalminutes = (endtime - m_printstarttime).TotalMinutes; m_printing = false; // mark printing doe //raise done message RaiseStatusEvent(eBuildStatus.eBuildStatusUpdate, "Build 100% Completed"); RaiseStatusEvent(eBuildStatus.eBuildCompleted, "Build Completed"); break; } } }
private void treeListBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { /* 0 stands for SB_HORZ */ int leftEdge = GetScrollPos(treeListBox.Handle, 0); if (leftEdge != this.leftEdge) { this.leftEdge = leftEdge; RedoColumnLayout(); } int position = 0; Graphics g = e.Graphics; ListBox treeView = treeListBox; if (e.Index < 0 || e.Index >= treeView.Items.Count) { return; } StringFormat sf = new StringFormat(StringFormatFlags.NoWrap); sf.Trimming = StringTrimming.EllipsisCharacter; TreeNodeBase node = (TreeNodeBase)Items[e.Index]; int crossover = (treeListBox.ItemHeight - 1) * (1 + node.depth); g.FillRectangle(new SolidBrush(Color.White), position, e.Bounds.Top, crossover, e.Bounds.Height); Rectangle itemRect = new Rectangle(crossover, e.Bounds.Top, e.Bounds.Right - crossover, e.Bounds.Height); g.FillRectangle(new SolidBrush(e.BackColor), itemRect); if (e.State == DrawItemState.Focus) { ControlPaint.DrawFocusRectangle(g, itemRect, e.ForeColor, e.BackColor); } Pen grayPen = new Pen(Color.LightGray); g.DrawLine(grayPen, 0, e.Bounds.Bottom - 1, e.Bounds.Right, e.Bounds.Bottom - 1); Font fontToUse = treeOwner.GetFont(TokenObject, node); Color color = treeOwner.GetColor(TokenObject, node, (e.State & DrawItemState.Selected) != DrawItemState.Selected); Brush brush = new SolidBrush(color); Region oldClip = g.Clip; foreach (Column c in columns) { ColumnInformation current = c.ColumnInformation; Rectangle rect = new Rectangle(position, e.Bounds.Top, c.Width, e.Bounds.Height); g.Clip = new Region(rect); string res = treeOwner.GetInfo(TokenObject, node, current).ToString(); if (current.ColumnType == ColumnInformation.ColumnTypes.Tree) { rect.Offset((1 + node.depth) * (treeListBox.ItemHeight - 1), 0); rect.Width -= (1 + node.depth) * (treeListBox.ItemHeight - 1); if (node.HasKids) { Pen p = new Pen(Color.Gray); int y0 = e.Bounds.Top; int x0 = position + node.depth * (treeListBox.ItemHeight - 1); g.DrawRectangle(p, x0 + 3, y0 + 3, (treeListBox.ItemHeight - 9), (treeListBox.ItemHeight - 9)); g.DrawLine(p, x0 + 5, y0 + (treeListBox.ItemHeight - 3) / 2, x0 + (treeListBox.ItemHeight - 8), y0 + (treeListBox.ItemHeight - 3) / 2); if (!node.IsExpanded) { g.DrawLine(p, x0 + (treeListBox.ItemHeight - 3) / 2, y0 + 5, x0 + (treeListBox.ItemHeight - 3) / 2, y0 + (treeListBox.ItemHeight - 8)); } } } if (res != null) { int characters, lines; SizeF layoutArea = new SizeF(rect.Width, rect.Height); SizeF stringSize = g.MeasureString(res, fontToUse, layoutArea, sf, out characters, out lines); g.DrawString(res.Substring(0, characters) + (characters < res.Length ? "..." : ""), fontToUse, brush, rect.Location, sf); g.DrawLine(grayPen, rect.Right - 1, e.Bounds.Top, rect.Right - 1, e.Bounds.Bottom - 1); } position += c.Width; } g.Clip = oldClip; }
public static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset, RightToLeft rightToLeft) { if (g == null) { throw new ArgumentNullException("g"); } if (backgroundImageLayout == ImageLayout.Tile) { using (TextureBrush brush = new TextureBrush(backgroundImage, WrapMode.Tile)) { if (scrollOffset != Point.Empty) { Matrix transform = brush.Transform; transform.Translate(scrollOffset.X, scrollOffset.Y); brush.Transform = transform; } g.FillRectangle(brush, clipRect); return; } } Rectangle rect = CalculateBackgroundImageRectangle(bounds, backgroundImage, backgroundImageLayout); if ((rightToLeft == RightToLeft.Yes) && (backgroundImageLayout == ImageLayout.None)) { rect.X += clipRect.Width - rect.Width; } using (SolidBrush brush2 = new SolidBrush(backColor)) { g.FillRectangle(brush2, clipRect); } if (!clipRect.Contains(rect)) { if ((backgroundImageLayout == ImageLayout.Stretch) || (backgroundImageLayout == ImageLayout.Zoom)) { rect.Intersect(clipRect); g.DrawImage(backgroundImage, rect); } else if (backgroundImageLayout == ImageLayout.None) { rect.Offset(clipRect.Location); Rectangle destRect = rect; destRect.Intersect(clipRect); Rectangle rectangle3 = new Rectangle(Point.Empty, destRect.Size); g.DrawImage(backgroundImage, destRect, rectangle3.X, rectangle3.Y, rectangle3.Width, rectangle3.Height, GraphicsUnit.Pixel); } else { Rectangle rectangle4 = rect; rectangle4.Intersect(clipRect); Rectangle rectangle5 = new Rectangle(new Point(rectangle4.X - rect.X, rectangle4.Y - rect.Y), rectangle4.Size); g.DrawImage(backgroundImage, rectangle4, rectangle5.X, rectangle5.Y, rectangle5.Width, rectangle5.Height, GraphicsUnit.Pixel); } } else { ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(backgroundImage, rect, 0, 0, backgroundImage.Width, backgroundImage.Height, GraphicsUnit.Pixel, imageAttr); imageAttr.Dispose(); } }
private void DrawMesh(object obj, EventArgs args) { Bitmap bmp = new Bitmap(canvas.Width, canvas.Height); Graphics g = Graphics.FromImage(bmp); Brush brush = new SolidBrush(Color.Black); // фон g.FillRectangle(brush, 0, 0, canvas.Width, canvas.Height); // матрицы поворота Matrix mRotX = new Matrix(); Matrix mRotY = new Matrix(); Matrix mRotZ = new Matrix(); // получаем координаты мыши Cursor = new Cursor(Cursor.Current.Handle); int xCoordinate = Cursor.Position.X; int yCoordinate = Cursor.Position.Y; theta = (float)yCoordinate / 50; fita = (float)xCoordinate / 50; // установка матрицы поворота вокруг оси Z mRotZ.cells[0, 0] = (float)Math.Cos(gamma); mRotZ.cells[0, 1] = (float)Math.Sin(gamma); mRotZ.cells[1, 0] = (float)-Math.Sin(gamma); mRotZ.cells[1, 1] = (float)Math.Cos(gamma); mRotZ.cells[2, 2] = 1; mRotZ.cells[3, 3] = 1; // установка матрицы поворота вокруг оси Y mRotY.cells[0, 0] = (float)Math.Cos(fita); mRotY.cells[0, 2] = (float)Math.Sin(fita); mRotY.cells[2, 0] = (float)-Math.Sin(fita); mRotY.cells[1, 1] = 1; mRotY.cells[2, 2] = (float)Math.Cos(fita); mRotY.cells[3, 3] = 1; // установка матрицы поворота вокруг оси X mRotX.cells[0, 0] = 1; mRotX.cells[1, 1] = (float)Math.Cos(theta * 0.5f); mRotX.cells[1, 2] = (float)Math.Sin(theta * 0.5f); mRotX.cells[2, 1] = (float)-Math.Sin(theta * 0.5f); mRotX.cells[2, 2] = (float)Math.Cos(theta * 0.5f); mRotX.cells[3, 3] = 1; canvas.Image = bmp; // отрисовка треугольников foreach (var tr in diamond.triangles) { var projected = new Triangle(); var moved = new Triangle(); var rotatedY = new Triangle(); var rotatedXY = new Triangle(); var rotatedXYZ = new Triangle(); // поворот вокруг оси Y MultiplyMatrixVector(tr.pnts[0], mRotY, out rotatedY.pnts[0]); MultiplyMatrixVector(tr.pnts[1], mRotY, out rotatedY.pnts[1]); MultiplyMatrixVector(tr.pnts[2], mRotY, out rotatedY.pnts[2]); // поворот вокруг оси X MultiplyMatrixVector(rotatedY.pnts[0], mRotX, out rotatedXY.pnts[0]); MultiplyMatrixVector(rotatedY.pnts[1], mRotX, out rotatedXY.pnts[1]); MultiplyMatrixVector(rotatedY.pnts[2], mRotX, out rotatedXY.pnts[2]); // поворот вокруг оси Z MultiplyMatrixVector(rotatedXY.pnts[0], mRotZ, out rotatedXYZ.pnts[0]); MultiplyMatrixVector(rotatedXY.pnts[1], mRotZ, out rotatedXYZ.pnts[1]); MultiplyMatrixVector(rotatedXY.pnts[2], mRotZ, out rotatedXYZ.pnts[2]); // сдвиг вдаль moved = rotatedXYZ; moved.pnts[0].z = rotatedXYZ.pnts[0].z + distanceToModel; moved.pnts[1].z = rotatedXYZ.pnts[1].z + distanceToModel; moved.pnts[2].z = rotatedXYZ.pnts[2].z + distanceToModel; // проекция в 2D MultiplyMatrixVector(moved.pnts[0], mProj, out projected.pnts[0]); MultiplyMatrixVector(moved.pnts[1], mProj, out projected.pnts[1]); MultiplyMatrixVector(moved.pnts[2], mProj, out projected.pnts[2]); // масштабирование projected.pnts[0].x += 1.0f; projected.pnts[0].y += 1.0f; projected.pnts[1].x += 1.0f; projected.pnts[1].y += 1.0f; projected.pnts[2].x += 1.0f; projected.pnts[2].y += 1.0f; projected.pnts[0].x *= 0.5f * canvas.Width; projected.pnts[0].y *= 0.5f * canvas.Height; projected.pnts[1].x *= 0.5f * canvas.Width; projected.pnts[1].y *= 0.5f * canvas.Height; projected.pnts[2].x *= 0.5f * canvas.Width; projected.pnts[2].y *= 0.5f * canvas.Height; DrawTriangle(g, projected.pnts[0].x, projected.pnts[0].y, projected.pnts[1].x, projected.pnts[1].y, projected.pnts[2].x, projected.pnts[2].y); } }
public Texture() { _thunderTimer = new Timer(); _animate = new Timer(); _animate.Start(); _animate.Interval = 10; _rainTimer = new Timer(); _rainTimer.Start(); _rainTimer.Interval = 10; _rainTimer.Tick += new EventHandler( T_rain_tick ); _thunderTimer.Start(); _thunderTimer.Interval = 10; _thunderTimer.Tick += new EventHandler(T_Thunder_tick); _animate.Tick += new EventHandler( T_animateTick ); _textureGrass = new Bitmap( @"..\..\..\assets\Grass.jpg"); _textureGrass2 = new Bitmap(@"..\..\..\assets\Grass2.jpg"); _textureForest = new Bitmap( @"..\..\..\assets\Forest.jpg" ); _textureSnow = new Bitmap( @"..\..\..\assets\Snow.jpg" ); _textureDesert = new Bitmap( @"..\..\..\assets\Desert.jpg" ); _textureDirt = new Bitmap( @"..\..\..\assets\Dirt.jpg" ); _textureMountain = new Bitmap(@"..\..\..\assets\Mountain.jpg"); _textureTree = new Bitmap( @"..\..\..\assets\Vegetation\Tree1.png" ); _textureTree2 = new Bitmap( @"..\..\..\assets\Vegetation\Tree2.png" ); _textureTree3 = new Bitmap( @"..\..\..\assets\Vegetation\Tree3.png" ); _textureBush = new Bitmap( @"..\..\..\assets\Vegetation\Bush1.png" ); _textureRock = new Bitmap( @"..\..\..\assets\Vegetation\Rock1.png" ); _textureRock2 = new Bitmap( @"..\..\..\assets\Vegetation\Rock2.png" ); _textureRock3 = new Bitmap( @"..\..\..\assets\Vegetation\Rock3.png" ); _textureRabbit = new Bitmap( @"..\..\..\assets\Animal\Rabbit.png" ); _textureElephant = new Bitmap( @"..\..\..\assets\Animal\Elephant.png" ); _textureElephant.RotateFlip(RotateFlipType.Rotate180FlipY); _textureCow = new Bitmap( @"..\..\..\assets\Animal\Cow.png" ); _textureCow.RotateFlip(RotateFlipType.Rotate180FlipY); _textureCat = new Bitmap( @"..\..\..\assets\Animal\Cat.png" ); _textureCat.MakeTransparent(Color.White); _textureCat.RotateFlip(RotateFlipType.Rotate180FlipY); _textureLion = new Bitmap(@"..\..\..\assets\Animal\Lion.png"); _textureLion.MakeTransparent(Color.White); _textureLion.RotateFlip(RotateFlipType.Rotate180FlipY); _textureEagle = new Bitmap(@"..\..\..\assets\Animal\Eagle.png"); _textureEagle.MakeTransparent(Color.White); _textureEagle.RotateFlip(RotateFlipType.Rotate180FlipY); _textureGazelle = new Bitmap( @"..\..\..\assets\Animal\Gazelle.png" ); _textureGazelle.MakeTransparent(Color.White); _textureGazelle.RotateFlip(RotateFlipType.Rotate180FlipY); _textureDog = new Bitmap( @"..\..\..\assets\Animal\Dog.png" ); _textureDog.MakeTransparent(Color.White); _textureDog.RotateFlip(RotateFlipType.Rotate180FlipY); _textureGiraffe = new Bitmap( @"..\..\..\assets\Animal\Elephant.png" ); _brushGrass = new SolidBrush( Color.FromArgb( 59, 138, 33 ) ); _brushDirt = new SolidBrush( Color.FromArgb( 169, 144, 104 ) ); _brushWater = new SolidBrush( Color.FromArgb( 64, 85, 213 ) ); _brushDesert = new SolidBrush( Color.FromArgb( 173, 128, 109 ) ); _brushForest = new SolidBrush( Color.FromArgb( 110, 121, 53 ) ); _brushSnow = new SolidBrush( Color.FromArgb( 207, 206, 212 ) ); _textureRain = new Bitmap( @"..\..\..\assets\Rain\0.gif" ); _textureRain.MakeTransparent( Color.Black ); _textureWaterAnimated = new Bitmap( @"..\..\..\assets\Water\Water.jpg" ); _textureThunder = new Bitmap(@"..\..\..\assets\Thunder\0.gif"); _textureThunder.MakeTransparent(Color.Black); AddTexturesFromFolderToList( @"..\..\..\assets\Animated\", _waterList ); AddTexturesFromFolderToList( @"..\..\..\assets\Rain\", _rainList ); AddTexturesFromFolderToList(@"..\..\..\assets\Thunder\", _thunderList); }
public frmHaklada() { InitializeComponent(); shadowBrush = new SolidBrush(Color.FromArgb(49, 106, 197)); }
/// <summary> /// 获取指定字符串的验证码图片 /// </summary> public Bitmap CreateImage(string code, ValidateCodeType codeType) { code.CheckNotNullOrEmpty("code"); int width = FontWidth * code.Length + FontWidth; int height = FontSize + FontSize / 2; const int flag = 255 / 2; bool isBgLight = (BgColor.R + BgColor.G + BgColor.B) / 3 > flag; Bitmap image = new Bitmap(width, height); Graphics grap = Graphics.FromImage(image); grap.Clear(BgColor); Brush brush = new SolidBrush(Color.FromArgb(255 - BgColor.R, 255 - BgColor.G, 255 - BgColor.B)); int x, y = 3; if (HasBorder) { grap.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); } Random rnd = Random; //绘制干扰线 for (int i = 0; i < RandomLineCount; i++) { x = rnd.Next(image.Width); y = rnd.Next(image.Height); int m = rnd.Next(image.Width); int n = rnd.Next(image.Height); Color lineColor = !RandomColor ? Color.FromArgb(90, 90, 90) : isBgLight ? Color.FromArgb(rnd.Next(130, 200), rnd.Next(130, 200), rnd.Next(130, 200)) : Color.FromArgb(rnd.Next(70, 150), rnd.Next(70, 150), rnd.Next(70, 150)); Pen pen = new Pen(lineColor, 2); grap.DrawLine(pen, x, y, m, n); } //绘制干扰点 for (int i = 0; i < (int)(image.Width * image.Height * RandomPointPercent / 100); i++) { x = rnd.Next(image.Width); y = rnd.Next(image.Height); Color pointColor = isBgLight ? Color.FromArgb(rnd.Next(30, 80), rnd.Next(30, 80), rnd.Next(30, 80)) : Color.FromArgb(rnd.Next(150, 200), rnd.Next(150, 200), rnd.Next(150, 200)); image.SetPixel(x, y, pointColor); } //绘制文字 for (int i = 0; i < code.Length; i++) { rnd = Random; x = FontWidth / 4 + FontWidth * i; if (RandomPosition) { x = rnd.Next(FontWidth / 4) + FontWidth * i; y = rnd.Next(image.Height / 5); } PointF point = new PointF(x, y); if (RandomColor) { int r, g, b; if (!isBgLight) { r = rnd.Next(255 - BgColor.R); g = rnd.Next(255 - BgColor.G); b = rnd.Next(255 - BgColor.B); if ((r + g + b) / 3 < flag) { r = 255 - r; g = 255 - g; b = 255 - b; } } else { r = rnd.Next(BgColor.R); g = rnd.Next(BgColor.G); b = rnd.Next(BgColor.B); if ((r + g + b) / 3 > flag) { r = 255 - r; g = 255 - g; b = 255 - b; } } brush = new SolidBrush(Color.FromArgb(r, g, b)); } string fontName = codeType == ValidateCodeType.Hanzi ? FontNamesForHanzi[rnd.Next(FontNamesForHanzi.Count)] : FontNames[rnd.Next(FontNames.Count)]; Font font = new Font(fontName, FontSize, FontStyle.Bold); if (RandomItalic) { grap.TranslateTransform(0, 0); Matrix transform = grap.Transform; transform.Shear(Convert.ToSingle(rnd.Next(2, 9) / 10d - 0.5), 0.001f); grap.Transform = transform; } grap.DrawString(code.Substring(i, 1), font, brush, point); grap.ResetTransform(); } return(image); }
private void DrawMapScale(Graphics g) { g.ResetTransform(); int scaleLen = 50; int meter = 0; switch (Zoom) { case 22: meter = 1; break; case 21: case 20: meter = 5; break; case 19: meter = 10; break; case 18: meter = 20; break; case 17: meter = 40; break; case 16: meter = 80; break; case 15: meter = 160; break; case 14: meter = 300; break; case 13: meter = 600; break; case 12: meter = 1000; break; case 11: meter = 2000; break; case 10: meter = 5000; break; case 9: meter = 10000; break; case 8: meter = 20000; break; case 7: meter = 40000; break; case 6: meter = 80000; break; case 5: meter = 150000; break; case 4: meter = 300000; break; case 3: meter = 600000; break; case 2: meter = 1000000; break; case 1: meter = 2000000; break; default: scaleLen = 50; break; } if (meter != 0) { scaleLen = (int)(meter / MercatorHelper.GetResolution(Zoom, MapCenter.LatY) + 0.5); } var dist = new Distance(meter); var str = dist.ToString(); //var str = distance.ToString("0.00") + "米"; var font = new Font("微软雅黑", 10, FontStyle.Bold); var strSize = g.MeasureString(str, font); var rect = new Rectangle(new Point(5, this.Height - 30), new Size(scaleLen + 10 + (int)strSize.Width, (int)strSize.Height + 5)); using (var gp = DrawHelper.GetRoundRect(rect, 5)) { g.FillPath(new SolidBrush(Color.FromArgb(0x44, Color.Black)), gp); } Point p = new Point(10, this.Height - 20); Point[] ps = new Point[4]; ps[0] = p; p.Offset(0, 5); ps[1] = p; p.Offset(scaleLen, 0); ps[2] = p; p.Offset(0, -5); ps[3] = p; var brush = new SolidBrush(Color.FromArgb(0xEE, Color.White)); var pen = new Pen(brush, 2); g.DrawLines(pen, ps); p.Offset(5, -10); g.DrawString(str, font, brush, p); }
/// <inheritdoc cref="GLOFC.GL4.Controls.GLBaseControl.Paint(Graphics)"/> protected override void Paint(Graphics gr) { Rectangle butarea = ClientRectangle; GLMenuStrip p = Parent as GLMenuStrip; bool ica = IconAreaEnable && p != null; if (ica) { butarea.Width -= p.IconAreaWidth; butarea.X += p.IconAreaWidth; } if (Enabled && (Highlighted || (Hover && !DisableHoverHighlight))) { base.PaintButtonFace(ClientRectangle, gr, MouseOverColor); } else { if (ica) { using (Brush br = new SolidBrush(p.IconStripBackColor)) { gr.FillRectangle(br, new Rectangle(0, 0, p.IconAreaWidth, ClientHeight)); } } base.PaintButtonFace(butarea, gr, Enabled ? ButtonFaceColour : ButtonFaceColour.Multiply(BackDisabledScaling)); } //using (Brush inner = new SolidBrush(Color.Red)) gr.FillRectangle(inner, butarea); // Debug base.PaintButtonTextImageFocus(butarea, gr, false); // don't paint the image if (ica) { int reduce = (int)(p.IconAreaWidth * TickBoxReductionRatio); Rectangle tickarea = new Rectangle((p.IconAreaWidth - reduce) / 2, (ClientHeight - reduce) / 2, reduce, reduce); if (CheckState != CheckStateType.Unchecked) { float discaling = Enabled ? 1.0f : BackDisabledScaling; Color checkboxbordercolour = CheckBoxBorderColor.Multiply(discaling); //(Enabled && Hover) ? MouseOverBackColor : Color backcolour = (Enabled && Hover) ? MouseOverColor : ButtonFaceColour.Multiply(discaling); using (Brush inner = new System.Drawing.Drawing2D.LinearGradientBrush(tickarea, CheckBoxInnerColor.Multiply(discaling), backcolour, 225)) gr.FillRectangle(inner, tickarea); // fill slightly over size to make sure all pixels are painted using (Pen outer = new Pen(checkboxbordercolour)) // paint over to ensure good boundary gr.DrawRectangle(outer, tickarea); } tickarea.Inflate(-1, -1); // reduce it around the drawn box above if (Image != null) // if we have an image, draw it into the tick area { base.DrawImage(Image, tickarea, gr, (Enabled) ? drawnImageAttributesEnabled : drawnImageAttributesDisabled); } else { base.DrawTick(tickarea, Color.FromArgb(200, CheckColor.Multiply(Enabled ? 1.0F : ForeDisabledScaling)), CheckState, gr); } } }
public Bitmap GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, Bitmap icon = null, int iconSizePercent = 15, int iconBorderWidth = 6, bool drawQuietZones = true) { var size = (this.QrCodeData.ModuleMatrix.Count - (drawQuietZones ? 0 : 8)) * pixelsPerModule; var offset = drawQuietZones ? 0 : 4 * pixelsPerModule; var bmp = new Bitmap(size, size, System.Drawing.Imaging.PixelFormat.Format24bppRgb); var gfx = Graphics.FromImage(bmp); gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.CompositingQuality = CompositingQuality.HighQuality; gfx.Clear(lightColor); var drawIconFlag = icon != null && iconSizePercent > 0 && iconSizePercent <= 100; GraphicsPath iconPath = null; float iconDestWidth = 0, iconDestHeight = 0, iconX = 0, iconY = 0; if (drawIconFlag) { iconDestWidth = iconSizePercent * bmp.Width / 100f; iconDestHeight = drawIconFlag ? iconDestWidth * icon.Height / icon.Width : 0; iconX = (bmp.Width - iconDestWidth) / 2; iconY = (bmp.Height - iconDestHeight) / 2; var centerDest = new RectangleF(iconX - iconBorderWidth, iconY - iconBorderWidth, iconDestWidth + iconBorderWidth * 2, iconDestHeight + iconBorderWidth * 2); iconPath = this.CreateRoundedRectanglePath(centerDest, iconBorderWidth * 2); } var lightBrush = new SolidBrush(lightColor); var darkBrush = new SolidBrush(darkColor); for (var x = 0; x < size + offset; x = x + pixelsPerModule) { for (var y = 0; y < size + offset; y = y + pixelsPerModule) { var module = this.QrCodeData.ModuleMatrix[(y + pixelsPerModule) / pixelsPerModule - 1][(x + pixelsPerModule) / pixelsPerModule - 1]; if (module) { var r = new Rectangle(x - offset, y - offset, pixelsPerModule, pixelsPerModule); if (drawIconFlag) { var region = new Region(r); region.Exclude(iconPath); gfx.FillRegion(darkBrush, region); } else { gfx.FillRectangle(darkBrush, r); } } else { gfx.FillRectangle(lightBrush, new Rectangle(x - offset, y - offset, pixelsPerModule, pixelsPerModule)); } } } if (drawIconFlag) { var iconDestRect = new RectangleF(iconX, iconY, iconDestWidth, iconDestHeight); gfx.DrawImage(icon, iconDestRect, new RectangleF(0, 0, icon.Width, icon.Height), GraphicsUnit.Pixel); } gfx.Save(); return(bmp); }
protected virtual void OnPaintForeground(PaintEventArgs e) { Color borderColor, foreColor; if (useCustomForeColor) { foreColor = ForeColor; if (isHovered && !isPressed && Enabled) { borderColor = MetroPaint.BorderColor.CheckBox.Hover(Theme); } else if (isHovered && isPressed && Enabled) { borderColor = MetroPaint.BorderColor.CheckBox.Press(Theme); } else if (!Enabled) { borderColor = MetroPaint.BorderColor.CheckBox.Disabled(Theme); } else { borderColor = MetroPaint.BorderColor.CheckBox.Normal(Theme); } } else { if (isHovered && !isPressed && Enabled) { foreColor = MetroPaint.ForeColor.CheckBox.Hover(Theme); borderColor = MetroPaint.BorderColor.CheckBox.Hover(Theme); } else if (isHovered && isPressed && Enabled) { foreColor = MetroPaint.ForeColor.CheckBox.Press(Theme); borderColor = MetroPaint.BorderColor.CheckBox.Press(Theme); } else if (!Enabled) { foreColor = MetroPaint.ForeColor.CheckBox.Disabled(Theme); borderColor = MetroPaint.BorderColor.CheckBox.Disabled(Theme); } else { foreColor = !useStyleColors?MetroPaint.ForeColor.CheckBox.Normal(Theme) : MetroPaint.GetStyleColor(Style); borderColor = MetroPaint.BorderColor.CheckBox.Normal(Theme); } } e.Graphics.SmoothingMode = SmoothingMode.HighQuality; using (Pen p = new Pen(borderColor)) { Rectangle boxRect = new Rectangle(0, Height / 2 - 6, 12, 12); e.Graphics.DrawEllipse(p, boxRect); } if (Checked) { Color fillColor = MetroPaint.GetStyleColor(Style); using (SolidBrush b = new SolidBrush(fillColor)) { Rectangle boxRect = new Rectangle(3, Height / 2 - 3, 6, 6); e.Graphics.FillEllipse(b, boxRect); } } e.Graphics.SmoothingMode = SmoothingMode.Default; Rectangle textRect = new Rectangle(16, 0, Width - 16, Height); TextRenderer.DrawText(e.Graphics, Text, MetroFonts.CheckBox(metroCheckBoxSize, metroCheckBoxWeight), textRect, foreColor, MetroPaint.GetTextFormatFlags(TextAlign)); OnCustomPaintForeground(new MetroPaintEventArgs(Color.Empty, foreColor, e.Graphics)); if (displayFocusRectangle && isFocused) { ControlPaint.DrawFocusRectangle(e.Graphics, ClientRectangle); } }
private void drawGraph(System.Drawing.Graphics formGraphics, int x, int y, int maxH, bool invertido, TaskbarMonitor.Counters.CounterInfo info, GraphTheme theme, CounterOptions opt) { var pos = maxH - ((info.CurrentValue * maxH) / info.MaximumValue); if (pos > Int32.MaxValue) { pos = Int32.MaxValue; } int posInt = Convert.ToInt32(pos) + y; var height = (info.CurrentValue * maxH) / info.MaximumValue; if (height > Int32.MaxValue) { height = Int32.MaxValue; } int heightInt = Convert.ToInt32(height); using (SolidBrush BrushBar = new SolidBrush(theme.BarColor)) { if (invertido) { formGraphics.FillRectangle(BrushBar, new Rectangle(x + Options.HistorySize, maxH, 4, heightInt)); } else { formGraphics.FillRectangle(BrushBar, new Rectangle(x + Options.HistorySize, posInt, 4, heightInt)); } } var initialGraphPosition = x + Options.HistorySize - info.History.Count; Point[] points = new Point[info.History.Count + 2]; int i = 0; int inverter = invertido ? -1 : 1; foreach (var item in info.History) { var heightItem = (item * maxH) / info.MaximumValue; if (heightItem > Int32.MaxValue) { height = Int32.MaxValue; } var convertido = Convert.ToInt32(heightItem); if (invertido) { points[i] = new Point(initialGraphPosition + i, 0 + convertido + y); } else { points[i] = new Point(initialGraphPosition + i, maxH - convertido + y); } i++; } if (invertido) { points[i] = new Point(initialGraphPosition + i, 0 + y); points[i + 1] = new Point(initialGraphPosition, 0 + y); } else { points[i] = new Point(initialGraphPosition + i, maxH + y); points[i + 1] = new Point(initialGraphPosition, maxH + y); } using (SolidBrush BrushGraph = new SolidBrush(theme.getNthColor(2, invertido ? 1 : 0))) { formGraphics.FillPolygon(BrushGraph, points); } }
private void drawStackedGraph(System.Drawing.Graphics formGraphics, int x, int y, int maxH, bool invertido, List <TaskbarMonitor.Counters.CounterInfo> infos, GraphTheme theme, CounterOptions opt) { float absMax = 0; List <float> lastValue = new List <float>(); // accumulate values for stacked effect List <List <float> > values = new List <List <float> >(); foreach (var info in infos.AsEnumerable().Reverse()) { absMax += info.MaximumValue; var value = new List <float>(); int z = 0; foreach (var item in info.History) { value.Add(item + (lastValue.Count > 0 ? lastValue.ElementAt(z) : 0)); z++; } values.Add(value); lastValue = value; } var historySize = values.Count > 0 ? values[0].Count : 0; // now we draw it var colors = theme.GetColorGradient(theme.StackedColors[0], theme.StackedColors[1], values.Count); int w = 0; if (!invertido) { values.Reverse(); } foreach (var info in values) { float currentValue = info.Count > 0 ? info.Last() : 0; var pos = maxH - ((currentValue * maxH) / absMax); if (pos > Int32.MaxValue) { pos = Int32.MaxValue; } int posInt = Convert.ToInt32(pos) + y; var height = (currentValue * maxH) / absMax; if (height > Int32.MaxValue) { height = Int32.MaxValue; } int heightInt = Convert.ToInt32(height); SolidBrush BrushBar = new SolidBrush(theme.BarColor); formGraphics.FillRectangle(BrushBar, new Rectangle(x + Options.HistorySize, posInt, 4, heightInt)); BrushBar.Dispose(); int i = 0; var initialGraphPosition = x + Options.HistorySize - historySize; Point[] points = new Point[historySize + 2]; foreach (var item in info) { var heightItem = (item * maxH) / absMax; if (heightItem > Int32.MaxValue) { heightItem = Int32.MaxValue; } var convertido = Convert.ToInt32(heightItem); points[i] = new Point(initialGraphPosition + i, maxH - convertido + y); i++; } points[i] = new Point(initialGraphPosition + i, maxH + y); points[i + 1] = new Point(initialGraphPosition, maxH + y); Brush brush = new SolidBrush(colors.ElementAt(w)); w++; formGraphics.FillPolygon(brush, points); brush.Dispose(); } }
private void PaintLine(LayoutLine line) { this.line = line; // Paint the last piece of the line RectangleF rcTrailer = line.Extent; float xMax = 0; if (line.Spans.Length > 0) { xMax = line.Spans[line.Spans.Length - 1].ContentExtent.Right; } var cx = extent.Width - xMax; if (cx > 0) { rcTrailer.X = xMax; rcTrailer.Width = cx; graphics.FillRectangle( styleStack.GetBackground(defaultBgColor), rcTrailer); } for (int iSpan = 0; iSpan < line.Spans.Length; ++iSpan) { this.span = line.Spans[iSpan]; this.styleStack.PushStyle(span.Style); var pos = new TextPointer(line.Position, iSpan, 0); var insideSelection = outer.ComparePositions(selStart, pos) <= 0 && outer.ComparePositions(pos, selEnd) < 0; this.fg = styleStack.GetForegroundColor(defaultFgColor); this.bg = styleStack.GetBackground(defaultBgColor); this.font = styleStack.GetFont(defaultFont); this.rcContent = span.ContentExtent; this.rcTotal = span.PaddedExtent; if (!insideSelection) { if (selStart.Line == line.Position && selStart.Span == iSpan) { // Selection starts inside the current span. Write // any unselected text first. if (selStart.Character > 0) { DrawTextSegment(0, selStart.Character, false); } if (selEnd.Line == line.Position && selEnd.Span == iSpan) { // Selection ends inside the current span. Write // selected text. DrawTextSegment(selStart.Character, selEnd.Character - selStart.Character, true); DrawTrailingTextSegment(selEnd.Character, false); } else { // Select all the way to the end of the span. DrawTrailingTextSegment(selStart.Character, true); } } else { // Not in selection at all. DrawText(span.Text, false); } } else { // Inside selection. Does it end? if (selEnd.Line == line.Position && selEnd.Span == iSpan) { // Selection ends inside the current span. Write // selected text. DrawTextSegment(0, selEnd.Character, true); DrawTrailingTextSegment(selEnd.Character, false); } else { DrawText(span.Text, true); } } #if DEBUG var text = span.Text; if (line.Position == selStart.Line && iSpan == selStart.Span) { var textFrag = text.Substring(0, selStart.Character); var sz = outer.MeasureText(graphics, textFrag, font); graphics.FillRectangle( Brushes.Red, span.ContentExtent.Left + sz.Width, line.Extent.Top, 1, line.Extent.Height); } if (line.Position == selEnd.Line && iSpan == selEnd.Span) { var textFrag = text.Substring(0, selEnd.Character); var sz = outer.MeasureText(graphics, textFrag, font); graphics.FillRectangle( Brushes.Blue, span.ContentExtent.Left + sz.Width, line.Extent.Top, 1, line.Extent.Height); } #endif styleStack.PopStyle(); } }