/// <summary>Initializes a new instance of the <see cref="T:System.Drawing.RectangleF"></see> class with the specified location and size.</summary> /// <param name="size">A <see cref="T:System.Drawing.SizeF"></see> that represents the width and height of the rectangular region. </param> /// <param name="location">A <see cref="T:System.Drawing.PointF"></see> that represents the upper-left corner of the rectangular region. </param> public RectangleF(Vector2 location, SizeF size) { this.x = location.X; this.y = location.Y; this.width = size.Width; this.height = size.Height; }
// Constructors. public RectangleF(PointF location, SizeF size) { x = location.X; y = location.Y; width = size.Width; height = size.Height; }
public MainForm () { // // _dataGridView // _dataGridView = new DataGridView (); _dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; _dataGridView.Dock = DockStyle.Fill; _dataGridView.TabIndex = 0; Controls.Add (_dataGridView); // // _textBoxColumn // _textBoxColumn = new DataGridViewTextBoxColumn (); _textBoxColumn.HeaderText = "ColumnA"; _textBoxColumn.Name = "ColumnA"; _dataGridView.Columns.Add (_textBoxColumn); // // MainForm // AutoScaleDimensions = new SizeF (6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size (292, 266); Location = new Point (200, 100); StartPosition = FormStartPosition.Manual; Text = "bug #80657"; Load += new EventHandler (MainForm_Load); }
public MainForm () { // // _tableLayoutPanel // _tableLayoutPanel = new TableLayoutPanel (); _tableLayoutPanel.AutoScroll = true; _tableLayoutPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink; _tableLayoutPanel.ColumnCount = 1; _tableLayoutPanel.ColumnStyles.Add (new ColumnStyle (SizeType.Percent, 100F)); _tableLayoutPanel.Dock = DockStyle.Fill; _tableLayoutPanel.RowCount = 5; _tableLayoutPanel.RowStyles.Add (new RowStyle ()); _tableLayoutPanel.RowStyles.Add (new RowStyle ()); _tableLayoutPanel.RowStyles.Add (new RowStyle ()); _tableLayoutPanel.RowStyles.Add (new RowStyle ()); _tableLayoutPanel.RowStyles.Add (new RowStyle ()); _tableLayoutPanel.TabIndex = 0; Controls.Add (_tableLayoutPanel); // // Form2 // AutoScaleDimensions = new SizeF (6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size (401, 368); Location = new Point (200, 100); StartPosition = FormStartPosition.Manual; Text = "bug #332892"; Load += new EventHandler (MainForm_Load); ResumeLayout (false); }
public MainForm () { // // _dataGridView // _dataGridView = new DataGridView (); _dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; _dataGridView.Location = new Point (26, 22); _dataGridView.Size = new Size (240, 221); _dataGridView.TabIndex = 0; Controls.Add (_dataGridView); // // _changeButton // _changeButton = new Button (); _changeButton.Location = new Point (97, 261); _changeButton.Size = new Size (112, 32); _changeButton.TabIndex = 1; _changeButton.Text = "&Change"; _changeButton.UseVisualStyleBackColor = true; _changeButton.Click += new EventHandler (ChangeButton_Click); Controls.Add (_changeButton); // // MainForm // AutoScaleDimensions = new SizeF (6F, 13F); AutoScaleMode = AutoScaleMode.Font; BackColor = Color.FromArgb (((int) (((byte) (220)))), ((int) (((byte) (220)))), ((int) (((byte) (255))))); ClientSize = new Size (292, 305); Location = new Point (200, 100); StartPosition = FormStartPosition.Manual; Text = "bug #78523"; Layout += new LayoutEventHandler (OnLayout); Load += new EventHandler (MainForm_Load); }
public MainForm () { // // _tableLayoutPanel // _tableLayoutPanel = new TableLayoutPanel (); _tableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; _tableLayoutPanel.ColumnCount = 3; _tableLayoutPanel.ColumnStyles.Add (new ColumnStyle ()); _tableLayoutPanel.ColumnStyles.Add (new ColumnStyle ()); _tableLayoutPanel.ColumnStyles.Add (new ColumnStyle ()); _tableLayoutPanel.Dock = DockStyle.Fill; _tableLayoutPanel.RowCount = 2; _tableLayoutPanel.RowStyles.Add (new RowStyle (SizeType.Percent, 50F)); _tableLayoutPanel.RowStyles.Add (new RowStyle (SizeType.Percent, 50F)); Controls.Add (_tableLayoutPanel); // // _buttonA // _buttonA = new Button (); _buttonA.TabIndex = 1; _buttonA.Text = "Button A"; _buttonA.UseVisualStyleBackColor = true; _tableLayoutPanel.Controls.Add (_buttonA, 0, 1); // // _buttonB // _buttonB = new Button (); _buttonB.TabIndex = 4; _buttonB.Text = "Button B"; _buttonB.UseVisualStyleBackColor = true; _tableLayoutPanel.Controls.Add (_buttonB, 2, 1); // // _label // _label = new Label (); _label.AutoSize = true; _label.Dock = DockStyle.Fill; _label.TabIndex = 6; _label.Text = "Label"; _tableLayoutPanel.Controls.Add (_label, 1, 1); // // _textBox // _textBox = new TextBox (); _textBox.Dock = DockStyle.Fill; _textBox.Multiline = true; _textBox.TabIndex = 7; _tableLayoutPanel.Controls.Add (_textBox, 1, 0); // // MainForm // AutoScaleDimensions = new SizeF (6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size (292, 300); Location = new Point (250, 100); StartPosition = FormStartPosition.Manual; Text = "bug #81843"; Load += new EventHandler (MainForm_Load); }
public void SizeToSizeF() { var size = new Size(10, 15); var actual = size.ToSizeF(); var expected = new SizeF(10, 15); Assert.AreEqual(expected, actual); }
private static void BuildLookupList(IDeviceContext g, Font font, ref SizeF[] size) { size = new SizeF[char.MaxValue]; for (var i = (char)0; i < (char)256; i++) { size[i] = MeasureString(g, font, i.ToString()); } }
/// <summary> /// Clamps point coordinate according to the specified size (0,0, size.Width, size.Height). /// </summary> /// <param name="point">The point to clamp.</param> /// <param name="size">The valid region.</param> /// <returns>Clamped point.</returns> public static PointF Clamp(this PointF point, SizeF size) { return new PointF { X = System.Math.Min(System.Math.Max(0, point.X), size.Width), Y = System.Math.Min(System.Math.Max(0, point.Y), size.Height) }; }
public void NonDefaultConstructorTest(float x, float y, float width, float height) { RectangleF rect1 = new RectangleF(x, y, width, height); PointF p = new PointF(x, y); SizeF s = new SizeF(width, height); RectangleF rect2 = new RectangleF(p, s); Assert.Equal(rect1, rect2); }
private static SizeF MeasureString(IDeviceContext g, IList text, Font font, FontData data) { SizeF ans = new SizeF(); foreach (char chr in text) { SizeF temp = MeasureString(g, chr, font, data); ans = new SizeF(ans.Width + temp.Width, temp.Height); } return ans; }
public void ResizeFactorConstructorFromSizeFToSizeNotPreservingProportions() { var from = new SizeF(123, 456); var to = new SizeF(456, 789); var factor = new ResizeFactor(from, to, false); var expectedHorizontalFactor = to.Width / from.Width; var expectedVerticalFactor = to.Height / from.Height; Assert.AreEqual(expectedHorizontalFactor, factor.Horizontal); Assert.AreEqual(expectedVerticalFactor, factor.Vertical); }
public ImageInlineObject(RenderTarget renderTarget, ImagingFactory wicFactory, string resourceName) { _renderTarget = renderTarget; using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream(resourceName)) { _bitmap = BitmapUtilities.LoadBitmapFromStream(renderTarget, wicFactory, stream); // Save the bitmap size, for faster access _bitmapSize = _bitmap.Size; } }
public void ArithmeticTestWithSizeF(float x, float y) { PointF p = new PointF(x, y); SizeF s = new SizeF(y, x); PointF addExpected = new PointF(x + y, y + x); PointF subExpected = new PointF(x - y, y - x); Assert.Equal(addExpected, p + s); Assert.Equal(subExpected, p - s); Assert.Equal(addExpected, PointF.Add(p, s)); Assert.Equal(subExpected, PointF.Subtract(p, s)); }
public void ArithmeticTest(float width, float height) { SizeF s1 = new SizeF(width, height); SizeF s2 = new SizeF(height, width); SizeF addExpected = new SizeF(width + height, width + height); SizeF subExpected = new SizeF(width - height, height - width); Assert.Equal(addExpected, s1 + s2); Assert.Equal(addExpected, SizeF.Add(s1, s2)); Assert.Equal(subExpected, s1 - s2); Assert.Equal(subExpected, SizeF.Subtract(s1, s2)); }
public void NonDefaultConstructorAndDimensionsTest(float width, float height) { SizeF s1 = new SizeF(width, height); PointF p1 = new PointF(width, height); SizeF s2 = new SizeF(s1); Assert.Equal(s1, s2); Assert.Equal(s1, new SizeF(p1)); Assert.Equal(s2, new SizeF(p1)); Assert.Equal(width, s1.Width); Assert.Equal(height, s1.Height); }
public MainForm () { ComponentResourceManager resources = new ComponentResourceManager (typeof (MainForm)); SuspendLayout (); // // _toolStrip // _toolStrip = new ToolStrip (); _toolStrip.Location = new Point (0, 24); _toolStrip.Name = "_toolStrip"; _toolStrip.Size = new Size (632, 25); _toolStrip.TabIndex = 1; _toolStrip.Text = "ToolStrip"; Controls.Add (_toolStrip); // // _newButton // _newButton = new ToolStripButton (); _newButton.DisplayStyle = ToolStripItemDisplayStyle.Image; _newButton.Image = ((Image) (resources.GetObject ("_newButton.Image"))); _newButton.ImageTransparentColor = Color.Black; _newButton.Text = "New"; _toolStrip.Items.Add (_newButton); // // _openButton // _openButton = new ToolStripButton (); _openButton.DisplayStyle = ToolStripItemDisplayStyle.Image; _openButton.Image = ((Image) (resources.GetObject ("_openButton.Image"))); _openButton.ImageTransparentColor = Color.Black; _openButton.Text = "Open"; _openButton.Click += new System.EventHandler (OpenFile); _toolStrip.Items.Add (_openButton); // // MainForm // AutoScaleDimensions = new SizeF (6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size (300, 300); IsMdiContainer = true; Location = new Point (250, 100); StartPosition = FormStartPosition.Manual; Text = "bug #81568"; Load += new EventHandler (MainForm_Load); ResumeLayout (false); PerformLayout (); }
public MainForm () { // // _label // _label = new Label (); _label.AutoSize = true; _label.Location = new Point (16, 19); _label.Margin = new Padding (4); _label.Text = "Ready"; _label.Size = new Size (36, 17); _label.TabIndex = 1; Controls.Add (_label); // // _button // _button = new Button (); _button.Location = new Point (130, 12); _button.Margin = new Padding (4); _button.Size = new Size (91, 28); _button.TabIndex = 2; _button.Text = "Start"; _button.UseVisualStyleBackColor = true; _button.Click += new EventHandler (Button_Click); _button.Visible = true; Controls.Add (_button); // // _backgroundWorker // _backgroundWorker = new BackgroundWorker (); _backgroundWorker.WorkerSupportsCancellation = true; _backgroundWorker.DoWork += new DoWorkEventHandler (OnDoWork); _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler (OnWorkDone); // // MainForm // AutoScaleDimensions = new SizeF (8F, 16F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size (184, 50); FormBorderStyle = FormBorderStyle.FixedDialog; Location = new Point (300, 100); StartPosition = FormStartPosition.Manual; Margin = new Padding (4); MaximizeBox = false; Text = "bug #373153"; Load += new EventHandler (MainForm_Load); }
public void DimensionsTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); PointF p = new PointF(x, y); SizeF s = new SizeF(width, height); Assert.Equal(p, rect.Location); Assert.Equal(s, rect.Size); Assert.Equal(x, rect.X); Assert.Equal(y, rect.Y); Assert.Equal(width, rect.Width); Assert.Equal(height, rect.Height); Assert.Equal(x, rect.Left); Assert.Equal(y, rect.Top); Assert.Equal(x + width, rect.Right); Assert.Equal(y + height, rect.Bottom); }
public void EqualityTest(float width, float height) { SizeF sLeft = new SizeF(width, height); SizeF sRight = new SizeF(height, width); if (width == height) { Assert.True(sLeft == sRight); Assert.False(sLeft != sRight); Assert.True(sLeft.Equals(sRight)); Assert.Equal(sLeft.GetHashCode(), sRight.GetHashCode()); return; } Assert.True(sLeft != sRight); Assert.False(sLeft == sRight); Assert.False(sLeft.Equals(sRight)); }
private void InitCallAndSendMsgBtns() { var image = UIImage.FromFile ("Images/Info/button.png"); _buttonSize = new SizeF (120, image.Size.Height); _btnCall = new UIButton (UIButtonType.RoundedRect); _btnCall.SetImage (new UIImage ("Images/Info/icon_phone.png"), UIControlState.Normal); _btnCall.SetStretchableImage ("Images/Info/button.png", "Images/Info/button_pressed.png"); _btnCall.ImageEdgeInsets = new UIEdgeInsets (0, 0, 10, 0); _btnSendMessage = new UIButton (UIButtonType.RoundedRect); _btnSendMessage.SetImage (new UIImage ("Images/Info/icon_mail.png"), UIControlState.Normal); _btnSendMessage.SetStretchableImage ("Images/Info/button.png", "Images/Info/button_pressed.png"); _btnSendMessage.ImageEdgeInsets = new UIEdgeInsets (0, 0, 10, 0); AddSubview (_btnCall); AddSubview (_btnSendMessage); }
public static GraphicsPath CreateRoundedRectangle(SizeF size, PointF location) { int cornerSize = (int)GraphConstants.CornerSize * 2; var height = size.Height; var width = size.Width; var left = location.X; var top = location.Y; var right = location.X + width; var bottom = location.Y + height; var path = new GraphicsPath(FillMode.Winding); path.AddArc(left, top, cornerSize, cornerSize, 180, 90); path.AddArc(right - cornerSize, top, cornerSize, cornerSize, 270, 90); path.AddArc(right - cornerSize, bottom - cornerSize, cornerSize, cornerSize, 0, 90); path.AddArc(left, bottom - cornerSize, cornerSize, cornerSize, 90, 90); path.CloseFigure(); return path; }
public static SizeF GetPreferredSize(this Control control, SizeF availableSize) { if (control == null) return Size.Empty; var mh = control.GetMacControl(); if (mh != null) { return mh.GetPreferredSize(availableSize); } var c = control.ControlObject as NSControl; if (c != null) { c.SizeToFit(); return c.Frame.Size.ToEto(); } var child = control.ControlObject as Control; return child == null ? SizeF.Empty : child.GetPreferredSize(availableSize); }
//生成缩略图 public void CreateThumbnailImage(string sFileSrcPath, string sFileDstPath, int iSizeLimit) { //检测源图片是否存在 if (File.Exists(sFileSrcPath)) { //获取源图片图像 System.Drawing.Image image = System.Drawing.Image.FromFile(sFileSrcPath); //定义一个大小结构 SizeF size = new SizeF(image.Width, image.Height); //计算出符合要求的大小 while (size.Width > iSizeLimit || size.Height > iSizeLimit)//51+aspx { size.Width /= 1.1F; size.Height /= 1.1F; } //创建缩略图图像 Bitmap bitmap = new Bitmap(Convert.ToInt16(size.Width), Convert.ToInt16(size.Height)); //创建缩略图绘画面 Graphics g = Graphics.FromImage(bitmap); //清除整个绘画面并以透明色填充 g.Clear(Color.Transparent); //定义源图像矩形区域 Rectangle Srcrect = new Rectangle(0, 0, image.Width, image.Height); //定义缩略图矩形区域 Rectangle Dstrect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); //绘制缩略图 g.DrawImage(bitmap, Dstrect, Srcrect, GraphicsUnit.Pixel); //保存为Jpeg图片 bitmap.Save(sFileDstPath, ImageFormat.Jpeg); //释放对象 g.Dispose(); image.Dispose(); bitmap.Dispose(); } }
public Image Mark(Image img, MarkType markType, string text, Image waterImg, int markx, int marky, bool bold, Color textColor, float transparence, FontFamily fontFamily) { //首先先判断该图片是否是 gif动画,如果为gif动画不对图片进行改动 foreach (Guid guid in img.FrameDimensionsList) { FrameDimension dimension = new FrameDimension(guid); if (img.GetFrameCount(dimension) > 1) { return(img); } } try { //添加文字水印 if (markType == MarkType.Text) { //根据源图片生成新的Bitmap对象作为作图区,为了给gif图片添加水印,才有此周折 Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb); //设置新建位图得分辨率 newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution); //创建Graphics对象,以对该位图进行操作 Graphics g = Graphics.FromImage(newBitmap); //消除锯齿 g.SmoothingMode = SmoothingMode.AntiAlias; //将原图拷贝到作图区 g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); //声明字体对象 Font cFont = null; //用来测试水印文本长度得尺子 SizeF size = new SizeF(); //探测出一个适合图片大小得字体大小,以适应水印文字大小得自适应 for (int i = 0; i < 6; i++) { //创建一个字体对象 cFont = new Font(fontFamily, sizes[i]); //是否加粗 if (!bold) { cFont = new Font(fontFamily, sizes[i], FontStyle.Regular); } else { cFont = new Font(fontFamily, sizes[i], FontStyle.Bold); } //测量文本大小 size = g.MeasureString(this.Text, cFont); //匹配第一个符合要求得字体大小 if ((ushort)size.Width < (ushort)img.Width) { break; } } //创建刷子对象,准备给图片写上文字 Brush brush = new SolidBrush(textColor); //在指定得位置写上文字 g.DrawString(text, cFont, brush, markx, marky); //释放Graphics对象 g.Dispose(); //将生成得图片读入MemoryStream System.IO.MemoryStream ms = new System.IO.MemoryStream(); newBitmap.Save(ms, ImageFormat.Jpeg); //重新生成Image对象 img = System.Drawing.Image.FromStream(ms); //返回新的Image对象 return(img); } //添加图像水印 else if (markType == MarkType.Image) { //获得水印图像 Image markImg = waterImg; //创建颜色矩阵 float[][] ptsArray = { new float[] { 1, 0, 0, 0, 0 }, new float[] { 0, 1, 0, 0, 0 }, new float[] { 0, 0, 1, 0, 0 }, new float[] { 0, 0, 0, transparence, 0 }, //注意:此处为0.0f为完全透明,1.0f为完全不透明 new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(ptsArray); //新建一个Image属性 ImageAttributes imageAttributes = new ImageAttributes(); //将颜色矩阵添加到属性 imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); //生成位图作图区 Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb); //设置分辨率 newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution); //创建Graphics Graphics g = Graphics.FromImage(newBitmap); //消除锯齿 g.SmoothingMode = SmoothingMode.AntiAlias; //拷贝原图到作图区 g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); //如果原图过小 if (markImg.Width > img.Width || markImg.Height > img.Height) { System.Drawing.Image.GetThumbnailImageAbort callb = null; //对水印图片生成缩略图,缩小到原图得1/4 System.Drawing.Image new_img = markImg.GetThumbnailImage(img.Width / 4, markImg.Height * img.Width / markImg.Width, callb, new System.IntPtr()); //添加水印 g.DrawImage(new_img, new Rectangle(markx, marky, new_img.Width, new_img.Height), 0, 0, new_img.Width, new_img.Height, GraphicsUnit.Pixel, imageAttributes); //释放缩略图 new_img.Dispose(); //释放Graphics g.Dispose(); //将生成得图片读入MemoryStream System.IO.MemoryStream ms = new System.IO.MemoryStream(); newBitmap.Save(ms, ImageFormat.Jpeg); //返回新的Image对象 img = Image.FromStream(ms); return(img); } //原图足够大 else { //添加水印 g.DrawImage(markImg, new Rectangle(markx, marky, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes); //释放Graphics g.Dispose(); //将生成得图片读入MemoryStream System.IO.MemoryStream ms = new System.IO.MemoryStream(); newBitmap.Save(ms, ImageFormat.Jpeg); //返回新的Image对象 img = Image.FromStream(ms); return(img); } } return(img); } catch { return(img); } }
private AppErrorDialog() { if (!appErrorInitialized) { Application.EnableVisualStyles(); appErrorInitialized = true; } string title = FL.AppErrorDialogTitle; string appName = FL.AppName; if (!string.IsNullOrEmpty(appName)) { title = appName + " – " + title; } AutoScaleDimensions = new SizeF(96, 96); AutoScaleMode = AutoScaleMode.Dpi; scaleFactor = CurrentAutoScaleDimensions.Width / 96; BackColor = SystemColors.Window; ControlBox = false; MinimizeBox = false; MaximizeBox = false; Font = SystemFonts.MessageBoxFont; FormBorderStyle = FormBorderStyle.FixedDialog; ShowInTaskbar = false; Size = new Size(Scale(550), Scale(350)); StartPosition = FormStartPosition.CenterScreen; Text = title; TopMost = true; tablePanel = new TableLayoutPanel(); tablePanel.Dock = DockStyle.Fill; tablePanel.RowCount = 6; tablePanel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); tablePanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); tablePanel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); tablePanel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); tablePanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 0)); tablePanel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); tablePanel.ColumnCount = 1; tablePanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); Controls.Add(tablePanel); introLabel = new Label(); introLabel.BackColor = Color.FromArgb(221, 74, 59); introLabel.ForeColor = Color.White; introLabel.Dock = DockStyle.Fill; introLabel.AutoSize = true; introLabel.Font = new Font( SystemFonts.MessageBoxFont.FontFamily, SystemFonts.MessageBoxFont.SizeInPoints * 1.3f, SystemFonts.MessageBoxFont.Style); introLabel.MaximumSize = new Size(ClientSize.Width, 0); introLabel.Padding = Scale(new Padding(6, 4, 7, 6)); introLabel.Margin = new Padding(); introLabel.UseCompatibleTextRendering = false; introLabel.UseMnemonic = false; tablePanel.Controls.Add(introLabel); tablePanel.SetRow(introLabel, 0); tablePanel.SetColumn(introLabel, 0); errorPanel = new Panel(); errorPanel.AutoScroll = true; errorPanel.Dock = DockStyle.Fill; errorPanel.Margin = Scale(new Padding(7, 8, 10, 6)); errorPanel.Padding = new Padding(); tablePanel.Controls.Add(errorPanel); tablePanel.SetRow(errorPanel, 1); tablePanel.SetColumn(errorPanel, 0); errorLabel = new Label(); errorLabel.AutoSize = true; // Always keep the vertical scrollbar width free because the label wouldn't get smaller // when the vertical scrollbar appears and then the horizontal scrollbar kicks in as well. errorLabel.MaximumSize = new Size(errorPanel.ClientSize.Width - SystemInformation.VerticalScrollBarWidth - 2, 0); errorLabel.Padding = new Padding(); errorLabel.Margin = new Padding(); errorLabel.UseCompatibleTextRendering = false; errorLabel.UseMnemonic = false; errorPanel.Controls.Add(errorLabel); logLabel = new LinkLabel(); logLabel.AutoSize = true; logLabel.MaximumSize = new Size(ClientSize.Width - Scale(20), 0); logLabel.Margin = Scale(new Padding(8, 6, 10, 0)); logLabel.Padding = new Padding(); if (FL.LogFileBasePath != null) { logLabel.Text = string.Format(FL.AppErrorDialogLogPath, FL.LogFileBasePath.Replace("\\", "\\\u200B") + "*.fl"); string dir = Path.GetDirectoryName(FL.LogFileBasePath).Replace("\\", "\\\u200B"); logLabel.LinkArea = new LinkArea(FL.AppErrorDialogLogPath.IndexOf("{0}", StringComparison.Ordinal), dir.Length); logLabel.LinkClicked += (s, e) => { Process.Start(Path.GetDirectoryName(FL.LogFileBasePath)); }; } else { logLabel.Text = FL.AppErrorDialogNoLog; logLabel.LinkArea = new LinkArea(0, 0); } logLabel.UseCompatibleTextRendering = false; logLabel.UseMnemonic = false; tablePanel.Controls.Add(logLabel); tablePanel.SetRow(logLabel, 2); tablePanel.SetColumn(logLabel, 0); detailsLabel = new LinkLabel(); detailsLabel.AutoSize = true; detailsLabel.Margin = Scale(new Padding(7, 6, 10, 10)); detailsLabel.Padding = new Padding(); detailsLabel.TabIndex = 11; detailsLabel.Text = FL.AppErrorDialogDetails; detailsLabel.UseCompatibleTextRendering = false; detailsLabel.Visible = CanShowDetails; tablePanel.Controls.Add(detailsLabel); tablePanel.SetRow(detailsLabel, 3); tablePanel.SetColumn(detailsLabel, 0); var attr = new TypeConverterAttribute(typeof(ExpandableObjectConverter)); TypeDescriptor.AddAttributes(typeof(Exception), attr); grid = new PropertyGrid(); grid.Dock = DockStyle.Fill; grid.Margin = Scale(new Padding(10, 10, 10, 10)); grid.ToolbarVisible = false; grid.HelpVisible = false; grid.PropertySort = PropertySort.Alphabetical; grid.UseCompatibleTextRendering = false; grid.Visible = false; tablePanel.Controls.Add(grid); tablePanel.SetRow(grid, 4); tablePanel.SetColumn(grid, 0); bool isGridColumnResized = false; grid.Resize += (s, e) => { if (!isGridColumnResized) { isGridColumnResized = true; // Source: http://stackoverflow.com/a/14475276/143684 FieldInfo fi = grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic); if (fi != null) { Control view = fi.GetValue(grid) as Control; if (view != null) { MethodInfo mi = view.GetType().GetMethod("MoveSplitterTo", BindingFlags.Instance | BindingFlags.NonPublic); if (mi != null) { mi.Invoke(view, new object[] { Scale(170) }); } mi = view.GetType().GetMethod("set_GrayTextColor", BindingFlags.Instance | BindingFlags.NonPublic); if (mi != null) { mi.Invoke(view, new object[] { Color.Black }); } } } } }; detailsLabel.LinkClicked += (s, e) => { detailsLabel.Hide(); int maxHeight = Screen.FromControl(this).Bounds.Height; int missingHeight = 0; int desiredHeight = Height + Scale(300); Height = desiredHeight; if (Height < desiredHeight) { // A window is automatically constrained to the size of its screen, so we can // compare the current size with what we had requested to know how much is // missing for the layout. missingHeight = desiredHeight - Height; } Top -= Scale(Math.Min(Top - 4, 150)); if (Top < 0) { Top = 0; } tablePanel.RowStyles[4].Height = Scale(350) - missingHeight; grid.Visible = true; }; buttonsPanel = new TableLayoutPanel(); buttonsPanel.AutoSize = true; buttonsPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink; buttonsPanel.BackColor = SystemColors.Control; buttonsPanel.Dock = DockStyle.Fill; buttonsPanel.Margin = new Padding(); buttonsPanel.Padding = Scale(new Padding(10, 10, 10, 10)); buttonsPanel.ColumnCount = 4; buttonsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); buttonsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); buttonsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); buttonsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); tablePanel.Controls.Add(buttonsPanel); tablePanel.SetRow(buttonsPanel, 5); tablePanel.SetColumn(buttonsPanel, 0); sendCheckBox = new CheckBox(); sendCheckBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom; sendCheckBox.AutoSize = true; sendCheckBox.Enabled = FL.CanSubmitLog; if (sendCheckBox.Enabled) { sendCheckBox.Checked = true; } sendCheckBox.FlatStyle = FlatStyle.System; sendCheckBox.Margin = new Padding(); sendCheckBox.Padding = new Padding(); sendCheckBox.Text = FL.AppErrorDialogSendLogs; sendCheckBox.UseCompatibleTextRendering = false; buttonsPanel.Controls.Add(sendCheckBox); buttonsPanel.SetRow(sendCheckBox, 0); buttonsPanel.SetColumn(sendCheckBox, 0); nextButton = new Button(); nextButton.AutoSize = true; nextButton.AutoSizeMode = AutoSizeMode.GrowAndShrink; nextButton.FlatStyle = FlatStyle.System; nextButton.Margin = Scale(new Padding(6, 0, 0, 0)); nextButton.Padding = Scale(new Padding(2, 1, 2, 1)); nextButton.Text = FL.AppErrorDialogNext; nextButton.UseCompatibleTextRendering = false; nextButton.UseVisualStyleBackColor = true; nextButton.Visible = false; nextButton.Click += (s, e) => { ShowNextError(); }; buttonsPanel.Controls.Add(nextButton); buttonsPanel.SetRow(nextButton, 0); buttonsPanel.SetColumn(nextButton, 1); terminateButton = new Button(); terminateButton.AutoSize = true; terminateButton.AutoSizeMode = AutoSizeMode.GrowAndShrink; terminateButton.FlatStyle = FlatStyle.System; terminateButton.Margin = Scale(new Padding(6, 0, 0, 0)); terminateButton.Padding = Scale(new Padding(2, 1, 2, 1)); terminateButton.Text = FL.AppErrorDialogTerminate; terminateButton.UseCompatibleTextRendering = false; terminateButton.UseVisualStyleBackColor = true; terminateButton.Click += (s, e) => { StartSubmitTool(); Close(); FL.Shutdown(); Environment.Exit(1); }; buttonsPanel.Controls.Add(terminateButton); buttonsPanel.SetRow(terminateButton, 0); buttonsPanel.SetColumn(terminateButton, 2); continueButton = new Button(); continueButton.AutoSize = true; continueButton.AutoSizeMode = AutoSizeMode.GrowAndShrink; continueButton.FlatStyle = FlatStyle.System; continueButton.Margin = Scale(new Padding(6, 0, 0, 0)); continueButton.Padding = Scale(new Padding(2, 1, 2, 1)); continueButton.Text = FL.AppErrorDialogContinue; continueButton.UseCompatibleTextRendering = false; continueButton.UseVisualStyleBackColor = true; continueButton.Click += (s, e) => { StartSubmitTool(); Close(); }; buttonsPanel.Controls.Add(continueButton); buttonsPanel.SetRow(continueButton, 0); buttonsPanel.SetColumn(continueButton, 3); }
/// <summary> /// Raises the Paint event /// </summary> /// <param name="e">A PaintCellEventArgs that contains the event data</param> protected override void OnPaint(PaintCellEventArgs e) { base.OnPaint(e); // don't bother going any further if the Cell is null if (e.Cell == null) { return; } Rectangle textRect = this.CalcButtonBounds(); textRect.Inflate(-4, -2); int imageWidth = 0; int textWidth = 0; if (e.Cell.Image != null) { Rectangle imageRect = this.CalcImageRect(e.Cell.Image, this.ImageAlignment); if (this.GetButtonRendererData(e.Cell).ButtonState == PushButtonStates.Pressed && !ThemeManager.VisualStylesEnabled) { imageRect.X += 1; imageRect.Y += 1; } this.DrawImage(e.Graphics, e.Cell.Image, imageRect, e.Enabled); imageWidth = imageRect.Width; } // draw the text if (e.Cell.Text != null && e.Cell.Text.Length != 0) { if (e.Enabled) { if (!ThemeManager.VisualStylesEnabled && this.GetButtonRendererData(e.Cell).ButtonState == PushButtonStates.Pressed) { textRect.X += 1; textRect.Y += 1; } // if the cell or the row it is in is selected // our forecolor will be the selection forecolor. // we'll ignore this and reset our forecolor to // that of the cell being rendered if (e.Selected) { this.ForeColor = e.Cell.ForeColor; } e.Graphics.DrawString(e.Cell.Text, this.Font, this.ForeBrush, textRect, this.StringFormat); } else { e.Graphics.DrawString(e.Cell.Text, this.Font, this.GrayTextBrush, textRect, this.StringFormat); } if (e.Cell.WidthNotSet) { SizeF size = e.Graphics.MeasureString(e.Cell.Text, this.Font); textWidth = (int)Math.Ceiling(size.Width); } } if (e.Cell.WidthNotSet) { e.Cell.ContentWidth = imageWidth + textWidth; } // draw focus if ((e.Focused && e.Enabled) // only if we want to show selection rectangle && (e.Table.ShowSelectionRectangle)) { Rectangle focusRect = this.CalcButtonBounds(); if (ThemeManager.VisualStylesEnabled) { focusRect.Inflate(-3, -3); if (this.GetButtonRendererData(e.Cell).ButtonState != PushButtonStates.Pressed) { ControlPaint.DrawFocusRectangle(e.Graphics, focusRect); } } else { focusRect.Inflate(-4, -4); ControlPaint.DrawFocusRectangle(e.Graphics, focusRect); } } }
void DrawStack(Graphics gr, int SizeY, int SizeX, int lineThick, bool legend, Color linesColor) { HClusterNode aux; while (nodesStack.Count > 0) { aux = nodesStack.Pop(); if (legend) { aux.gNode.DrawNode(gr, lineThick); } if (nodesStack.Count == 0) { continue; } Pen p; if (linesColor == Color.Empty) { p = new Pen(aux.color); } else { p = new Pen(linesColor); } // p = new Pen(Color.Black); p.Width = lineThick; if (aux.parent != null) { if (horizontalView) { int x = aux.gNode.x; gr.DrawLine(p, x, aux.gNode.y, x, aux.parent.gNode.y - lineThick / 2); int y = aux.parent.gNode.y; gr.DrawLine(p, aux.gNode.x, y, aux.parent.gNode.x, y); } else { int y = aux.gNode.y; gr.DrawLine(p, aux.gNode.x, y, aux.parent.gNode.x - lineThick / 2, y); int x = aux.parent.gNode.x; gr.DrawLine(p, x, aux.gNode.y, x, aux.parent.gNode.y); } //Console.WriteLine("x=" + x + " y=" + aux.gNode.y + " x=" + x + " y=" + (aux.parent.gNode.y - lineThick / 2)); } if (aux.joined == null) { if (vecColor != null) { if (vecColor.ContainsKey(aux.refStructure)) { Pen r = new Pen(classColor[vecColor[aux.refStructure]]); r.Width = lineThick; gr.DrawLine(r, aux.gNode.x, aux.gNode.y, aux.gNode.x, SizeY); } } if (showLabels) { string label = aux.refStructure; Font drawFont = new System.Drawing.Font("Arial", labelSize); SolidBrush drawBrush; drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); SizeF ss = gr.MeasureString(aux.refStructure, drawFont); if (horizontalView) { gr.TranslateTransform(aux.gNode.x, SizeY - ss.Width); gr.RotateTransform(90); gr.DrawString(label, drawFont, drawBrush, 0, 0); gr.RotateTransform(-90); gr.ResetTransform(); } else { // gr.DrawString(label, drawFont, drawBrush, aux.gNode.x-ss.Width, aux.gNode.y-6); gr.DrawString(label, drawFont, drawBrush, SizeX - ss.Width, aux.gNode.y - 6); } } } } }
private void goGenerateProcessesFriendship() { spaceForProcesses.Left = 150; spaceForProcesses.Width = spaceForProcesses.Width - 150; spaceForProcesses.Top = bottomPanel.Top; spaceForProcesses.Height = bottomPanel.Height; spaceForProcesses.Invalidate(); foreach (var theProcess in Process.GetProcesses()) { Label hmGreatJobFantasticAmazing = new Label(); // hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Center; if (theProcess.MainWindowTitle != "") { //hmGreatJobFantasticAmazing.Text = theProcess.MainWindowTitle; hmGreatJobFantasticAmazing.Margin = new Padding(6, 0, 6, 0); hmGreatJobFantasticAmazing.Visible = true; // hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 13, FontStyle.Italic); Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap().Save(@"C:\ProjectSnowshoes\temptaskico.png"); DualImageForm thanksVKLines = new DualImageForm(); thanksVKLines.pic = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); thanksVKLines.analyze(); thanksVKLines.pic2.Save(@"C:\ProjectSnowshoes\newtemptaskico.png"); ImageFactory grayify = new ImageFactory(); grayify.Load(@"C:\ProjectSnowshoes\temptaskico.png"); //grayify.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); //grayify.Tint(Color.FromName("Gray")); hmGreatJobFantasticAmazing.Image = grayify.Image; Label areYouSeriouslyStillDoingThisLetItGo = new Label(); hmGreatJobFantasticAmazing.Click += (sender, args) => { System.Diagnostics.Process.Start(theProcess.Modules[0].FileName); }; hmGreatJobFantasticAmazing.MouseHover += (sender, args) => { int recordNao = hmGreatJobFantasticAmazing.Left; //hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Zoom; //hmGreatJobFantasticAmazing.Height = 75; /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleLeft; * hmGreatJobFantasticAmazing.AutoEllipsis = true; * hmGreatJobFantasticAmazing.Width = 250; * hmGreatJobFantasticAmazing.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); * hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); * hmGreatJobFantasticAmazing.ForeColor = Color.White; * * hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft; * hmGreatJobFantasticAmazing.Text = " " + theProcess.MainWindowTitle;*/ hmGreatJobFantasticAmazing.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); areYouSeriouslyStillDoingThisLetItGo.Left = recordNao + 150; areYouSeriouslyStillDoingThisLetItGo.Text = theProcess.MainWindowTitle; areYouSeriouslyStillDoingThisLetItGo.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); areYouSeriouslyStillDoingThisLetItGo.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); areYouSeriouslyStillDoingThisLetItGo.ForeColor = Color.White; areYouSeriouslyStillDoingThisLetItGo.TextAlign = ContentAlignment.MiddleLeft; panel1.Controls.Add(areYouSeriouslyStillDoingThisLetItGo); //Measuring string turnt-up-edness was guided by an answer on Stack Overflow by Tom Anderson. Graphics heyGuessWhatGraphicsYeahThatsRight = Graphics.FromImage(new Bitmap(1, 1)); SizeF sure = heyGuessWhatGraphicsYeahThatsRight.MeasureString(theProcess.MainWindowTitle, new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular, GraphicsUnit.Point)); Size sureAgain = sure.ToSize(); if (sureAgain.Width >= 300) { areYouSeriouslyStillDoingThisLetItGo.Width = sureAgain.Width + 10; } else { areYouSeriouslyStillDoingThisLetItGo.Width = 300; } areYouSeriouslyStillDoingThisLetItGo.Height = bottomPanel.Height; areYouSeriouslyStillDoingThisLetItGo.Top = Screen.PrimaryScreen.WorkingArea.Height - bottomPanel.Height; areYouSeriouslyStillDoingThisLetItGo.Show(); areYouSeriouslyStillDoingThisLetItGo.Visible = true; areYouSeriouslyStillDoingThisLetItGo.BringToFront(); areYouSeriouslyStillDoingThisLetItGo.Invalidate(); //hmGreatJobFantasticAmazing.BringToFront(); //panel1.Controls.Add(hmGreatJobFantasticAmazing); //hmGreatJobFantasticAmazing.Top = bottomPanel.Top - 40; //hmGreatJobFantasticAmazing.Left = recordNao + 150; //hmGreatJobFantasticAmazing.BringToFront(); //hmGreatJobFantasticAmazing.Invalidate(); /*hmGreatJobFantasticAmazing.Height = 100; * hmGreatJobFantasticAmazing.Width = 100;*/ }; hmGreatJobFantasticAmazing.MouseLeave += (sender, args) => { /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleCenter; * hmGreatJobFantasticAmazing.AutoEllipsis = false; * hmGreatJobFantasticAmazing.Width = 40; * hmGreatJobFantasticAmazing.BackColor = Color.Transparent; * //hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); * //hmGreatJobFantasticAmazing.ForeColor = Color.White; * * hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft; * hmGreatJobFantasticAmazing.Text = "";*/ panel1.Controls.Remove(areYouSeriouslyStillDoingThisLetItGo); hmGreatJobFantasticAmazing.BackColor = Color.Transparent; }; openFileToolTip.SetToolTip(hmGreatJobFantasticAmazing, theProcess.MainWindowTitle); //hmGreatJobFantasticAmazing.BackgroundImage = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); hmGreatJobFantasticAmazing.Height = bottomPanel.Height; hmGreatJobFantasticAmazing.Width = 40; spaceForProcesses.Controls.Add(hmGreatJobFantasticAmazing); } } }
public static sd.SizeF ToSD(this SizeF size) { return(new sd.SizeF(size.Width, size.Height)); }
public virtual void DrawThumbnail(IDocument doc, IGraphics g, SizeF size, Theme theme) { g.SetColor(GetThumbnailBackgroundColor(theme)); g.FillRect(new RectangleF(PointF.Empty, size)); }
private void InitializeComponent() { _panelMessage = new KryptonPanel(); _textBoxResponse = new KryptonTextBox(); _labelPrompt = new KryptonWrapLabel(); _buttonCancel = new KryptonButton(); _buttonOK = new KryptonButton(); ((ISupportInitialize)(_panelMessage)).BeginInit(); _panelMessage.SuspendLayout(); SuspendLayout(); // // _panelMessage // _panelMessage.Controls.Add(_textBoxResponse); _panelMessage.Controls.Add(_labelPrompt); _panelMessage.Controls.Add(_buttonCancel); _panelMessage.Controls.Add(_buttonOK); _panelMessage.Dock = DockStyle.Fill; _panelMessage.Location = new Point(0, 0); _panelMessage.Name = "_panelMessage"; _panelMessage.Size = new Size(357, 118); _panelMessage.TabIndex = 0; // // _textBoxResponse // _textBoxResponse.Location = new Point(12, 86); _textBoxResponse.Name = "_textBoxResponse"; _textBoxResponse.Size = new Size(333, 20); _textBoxResponse.TabIndex = 0; // // _labelPrompt // _labelPrompt.AutoSize = false; _labelPrompt.Font = new Font("Segoe UI", 9F); _labelPrompt.ForeColor = Color.FromArgb(30, 57, 91); _labelPrompt.LabelStyle = LabelStyle.NormalPanel; _labelPrompt.Location = new Point(12, 12); _labelPrompt.Margin = new Padding(0); _labelPrompt.Name = "_labelPrompt"; _labelPrompt.Size = new Size(78, 15); _labelPrompt.Text = "Prompt"; // // _buttonCancel // _buttonCancel.Anchor = AnchorStyles.Top | AnchorStyles.Right; _buttonCancel.AutoSize = true; _buttonCancel.DialogResult = DialogResult.Cancel; _buttonCancel.Location = new Point(295, 43); _buttonCancel.Margin = new Padding(0); _buttonCancel.MinimumSize = new Size(50, 26); _buttonCancel.Name = "_buttonCancel"; _buttonCancel.Size = new Size(50, 26); _buttonCancel.TabIndex = 2; _buttonCancel.Values.Text = "Cancel"; _buttonCancel.KeyDown += button_keyDown; // // _buttonOK // _buttonOK.Anchor = AnchorStyles.Top | AnchorStyles.Right; _buttonOK.AutoSize = true; _buttonOK.DialogResult = DialogResult.OK; _buttonOK.Location = new Point(295, 12); _buttonOK.Margin = new Padding(0); _buttonOK.MinimumSize = new Size(50, 26); _buttonOK.Name = "_buttonOK"; _buttonOK.Size = new Size(50, 26); _buttonOK.TabIndex = 1; _buttonOK.Values.Text = "OK"; _buttonOK.KeyDown += button_keyDown; // // KryptonInputBox // AutoScaleDimensions = new SizeF(6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(357, 118); Controls.Add(_panelMessage); FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; MinimizeBox = false; Name = "KryptonInputBox"; ShowIcon = false; ShowInTaskbar = false; SizeGripStyle = SizeGripStyle.Hide; StartPosition = FormStartPosition.CenterParent; ((ISupportInitialize)(_panelMessage)).EndInit(); _panelMessage.ResumeLayout(false); _panelMessage.PerformLayout(); ResumeLayout(false); }
/// <summary> /// Creates PDF /// </summary> public void CreatePDF(IList <InvoiceItem> dataSource, BillingInformation billInfo, double totalDue) { PdfDocument document = new PdfDocument(); document.PageSettings.Orientation = PdfPageOrientation.Portrait; document.PageSettings.Margins.All = 50; PdfPage page = document.Pages.Add(); PdfGraphics g = page.Graphics; PdfTextElement element = new PdfTextElement(@"Syncfusion Software 2501 Aerial Center Parkway Suite 200 Morrisville, NC 27560 USA Tel +1 888.936.8638 Fax +1 919.573.0306"); element.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12); element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); PdfLayoutResult result = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200)); Assembly assembly = typeof(MainPage).Assembly; Stream imgStream = assembly.GetManifestResourceStream("Invoice.Assets.SyncfusionLogo.jpg"); PdfImage img = PdfImage.FromStream(imgStream); page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45)); PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); g.DrawRectangle(new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30)); element = new PdfTextElement("INVOICE " + billInfo.InvoiceNumber.ToString(), subHeadingFont); element.Brush = PdfBrushes.White; result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48)); string currentDate = "DATE " + billInfo.Date.ToString("d"); SizeF textSize = subHeadingFont.MeasureString(currentDate); g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y)); element = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); element.Brush = new PdfSolidBrush(new PdfColor(34, 83, 142)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); g.DrawLine(new PdfPen(new PdfColor(34, 83, 142), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3)); element = new PdfTextElement(billInfo.Name, new PdfStandardFont(PdfFontFamily.TimesRoman, 11)); element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); result = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100)); element = new PdfTextElement(billInfo.Address, new PdfStandardFont(PdfFontFamily.TimesRoman, 11)); element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); result = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100)); PdfGrid grid = new PdfGrid(); grid.DataSource = ConvertToDataTable(dataSource); PdfGridCellStyle cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; PdfGridRow header = grid.Headers[0]; PdfGridCellStyle headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(34, 83, 142)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(34, 83, 142)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular); for (int i = 0; i < header.Cells.Count; i++) { if (i == 0) { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } } header.Cells[0].Value = "ITEM"; header.Cells[1].Value = "QUANTITY"; header.Cells[2].Value = "RATE"; header.Cells[3].Value = "TAXES"; header.Cells[4].Value = "AMOUNT"; header.ApplyStyle(headerStyle); grid.Columns[0].Width = 180; cellStyle.Borders.Bottom = new PdfPen(new PdfColor(34, 83, 142), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); foreach (PdfGridRow row in grid.Rows) { row.ApplyStyle(cellStyle); for (int i = 0; i < row.Cells.Count; i++) { PdfGridCell cell = row.Cells[i]; if (i == 0) { cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } if (i > 1) { if (cell.Value.ToString().Contains("$")) { cell.Value = cell.Value.ToString(); } else { if (cell.Value is double) { cell.Value = "$" + ((double)cell.Value).ToString("#,###.00", CultureInfo.InvariantCulture); } else { cell.Value = "$" + cell.Value.ToString(); } } } } } PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat(); layoutFormat.Layout = PdfLayoutType.Paginate; PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat); float pos = 0.0f; for (int i = 0; i < grid.Columns.Count - 1; i++) { pos += grid.Columns[i].Width; } PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold); gridResult.Page.Graphics.DrawString("TOTAL DUE", font, new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 10), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right)); gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(0, 0, 0)), new PointF(pos - 210, gridResult.Bounds.Bottom + 60)); pos += grid.Columns[4].Width; gridResult.Page.Graphics.DrawString("$" + totalDue.ToString("#,###.00", CultureInfo.InvariantCulture), font, new PdfSolidBrush(new PdfColor(0, 0, 0)), new RectangleF(pos, gridResult.Bounds.Bottom + 10, grid.Columns[4].Width - pos, 20), new PdfStringFormat(PdfTextAlignment.Right)); document.Save("Invoice.pdf"); //Message box confirmation to view the created PDF document. if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { //Launching the PDF file using the default Application.[Acrobat Reader] #if !NETCORE System.Diagnostics.Process.Start("Invoice.pdf"); #else ProcessStartInfo psi = new ProcessStartInfo { FileName = "cmd", WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, CreateNoWindow = true, Arguments = "/c start Invoice.pdf" }; Process.Start(psi); #endif //this.Close(); } //else // Exit //this.Close(); document.Close(true); }
/// <summary> /// 获取节点文本绘制的坐标 /// </summary> /// <param name="e.Node"></param> /// <param name="p_strText"></param> /// <param name="p_font"></param> /// <returns></returns> private PointF GetTextPoint(DrawTreeNodeEventArgs e, string p_strText, Font p_font) { Graphics l_graphics = this.CreateGraphics(); SizeF l_sizeF = l_graphics.MeasureString(p_strText, p_font); //计算文本的宽高 int l_nWidth = e.Bounds.Width; int l_nHeight = e.Bounds.Height; PointF l_pointF = new PointF(e.Bounds.Left + (l_nWidth - (int)l_sizeF.Width) / 2, //默认居中 e.Bounds.Top + (l_nHeight - (int)l_sizeF.Height) / 2); if (e.Bounds.Width == 0 && e.Bounds.Height == 0) //去除打开节点时节点DrawTreeNodeEventArgs参数都为0时导致绘图出现残影 { return(new PointF(-10000, -10000)); } switch (m_nTextAlign) { case (int)ContentAlignment.TopLeft: { l_pointF.X = e.Bounds.Left + (e.Node.Level * this.Indent); if (m_nNodeImageAlign == 0 && this.ImageList != null) //显示图标时调整文本显示坐标 { l_pointF.X += (this.ImageList.ImageSize.Width + 2); } l_pointF.Y = e.Bounds.Top + 1; break; } case (int)ContentAlignment.TopCenter: { l_pointF.Y = e.Bounds.Top + 1; break; } case (int)ContentAlignment.TopRight: { l_pointF.X = e.Bounds.Right - (int)l_sizeF.Width - 1; if (m_nNodeImageAlign == 1 && this.ImageList != null) { l_pointF.X -= (this.ImageList.ImageSize.Width + 2); } l_pointF.Y = e.Bounds.Top + 1; break; } case (int)ContentAlignment.MiddleLeft: { l_pointF.X = e.Bounds.Left + (e.Node.Level * this.Indent); if (m_nNodeImageAlign == 0 && this.ImageList != null) { l_pointF.X += (this.ImageList.ImageSize.Width + 2); } break; } case (int)ContentAlignment.MiddleCenter: { //默认 break; } case (int)ContentAlignment.MiddleRight: { l_pointF.X = e.Bounds.Right - (int)l_sizeF.Width - 1; if (m_nNodeImageAlign == 1 && this.ImageList != null) { l_pointF.X -= (this.ImageList.ImageSize.Width + 2); } break; } case (int)ContentAlignment.BottomLeft: { l_pointF.X = e.Bounds.Left + (e.Node.Level * this.Indent); if (m_nNodeImageAlign == 0 && this.ImageList != null) { l_pointF.X += (this.ImageList.ImageSize.Width + 2); } l_pointF.Y = e.Bounds.Bottom - (int)l_sizeF.Height - 1; break; } case (int)ContentAlignment.BottomCenter: { l_pointF.Y = e.Bounds.Bottom - (int)l_sizeF.Height - 1; break; } case (int)ContentAlignment.BottomRight: { l_pointF.X = e.Bounds.Right - (int)l_sizeF.Width - 1; if (m_nNodeImageAlign == 1 && this.ImageList != null) { l_pointF.X -= (this.ImageList.ImageSize.Width + 2); } l_pointF.Y = e.Bounds.Bottom - (int)l_sizeF.Height - 1; break; } default: { //默认 break; } } return(l_pointF); }
private void canvas_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.Clear(Color.White); // 頂点の描画 if (appGraph != null) { // appGraph, appendingNodeの描画 for (int i = 0; i < appGraph.nodes.Count; i++) { AppNode node = appGraph.nodes[i]; g.DrawImage(node.Icon, new Rectangle(node.Position, nodeSize)); try { if (node.Process != null) { string text = NodeTitle(node); if (text.Length >= AppNodeTitleCharLimit) { text = text.Remove(AppNodeTitleCharLimit - 4) + "..."; } SizeF textSize = g.MeasureString(text, fnt); float textX = node.Position.X + nodeSize.Width / 2 - textSize.Width / 2; float textY = node.Position.Y + nodeSize.Height; g.DrawString(text, fnt, Brushes.Black, new PointF(textX, textY)); } } catch (Exception ee) { Console.WriteLine(ee); } } } if (appendingNode != null) { g.DrawImage(appendingNode.Icon, new Rectangle(appendingNode.Position, nodeSize)); } // 枝の描画 if (appGraph != null) { for (int i = 0; i < appGraph.edges.Count; i++) { AppEdge edge = appGraph.edges[i]; Point p1, p2, p3, p4; EdgePoints(edge.Src, edge.Dst, out p1, out p2, out p3, out p4); if (edge.Src != edge.Dst) { g.DrawLine(edgePen, p3, p4); } else { g.DrawArc(edgePen, new Rectangle(p1.X, p1.Y - 64, 64, 64), 90, -270); } // TODO string text = ""; if (edge.ActionHandler.TriggerType == TriggerType.ContextMenu) { text = "\"" + edge.ActionHandler.ContextMenuText + "\""; } else { text += edge.ActionHandler.Ctrl ? "Ctrl + " : ""; text += edge.ActionHandler.Win ? "Ctrl + " : ""; text += edge.ActionHandler.Fn ? "Fn + " : ""; text += edge.ActionHandler.Shift ? "Sfhift + " : ""; text += edge.ActionHandler.Alt ? "Alt + " : ""; text += edge.ActionHandler.Key; } g.DrawString(text, fnt, Brushes.Black, new PointF((p1.X + p4.X) / 2, (p1.Y + p4.Y) / 2)); } } if (appendingEdge != null) { Point srcPos = new Point( appendingEdge.Src.Position.X + nodeSize.Width / 2, appendingEdge.Src.Position.Y + nodeSize.Height / 2); Point dstPos = canvas.PointToClient(Cursor.Position); g.DrawLine(edgePen, srcPos, dstPos); } }
public void InflateTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); RectangleF inflatedRect = new RectangleF(x - width, y - height, width + 2 * width, height + 2 * height); rect.Inflate(width, height); Assert.Equal(inflatedRect, rect); SizeF s = new SizeF(x, y); inflatedRect = RectangleF.Inflate(rect, x, y); rect.Inflate(s); Assert.Equal(inflatedRect, rect); }
protected override void OnPaint(PaintEventArgs e) { G = e.Graphics; G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; G.Clear(BackColor); G.SmoothingMode = SmoothingMode.AntiAlias; GP1 = ThemeModule.CreateRound(0, 0, Width - 1, Height - 1, 7); GP2 = ThemeModule.CreateRound(1, 1, Width - 3, Height - 3, 7); GB1 = new LinearGradientBrush(ClientRectangle, Color.FromArgb(60, 60, 60), Color.FromArgb(55, 55, 55), 90f); G.SetClip(GP1); G.FillRectangle(GB1, ClientRectangle); G.ResetClip(); G.DrawPath(P1, GP1); G.DrawPath(P4, GP2); SZ1 = G.MeasureString(Text, Font); PT1 = new PointF(5, Height / 2 - SZ1.Height / 2); G.DrawString(Text, Font, Brushes.Black, PT1.X + 1, PT1.Y + 1); G.DrawString(Text, Font, Brushes.White, PT1); G.DrawLine(P3, Width - 15, 10, Width - 11, 13); G.DrawLine(P3, Width - 7, 10, Width - 11, 13); G.DrawLine(Pens.Black, Width - 11, 13, Width - 11, 14); G.DrawLine(P2, Width - 16, 9, Width - 12, 12); G.DrawLine(P2, Width - 8, 9, Width - 12, 12); G.DrawLine(Pens.White, Width - 12, 12, Width - 12, 13); G.DrawLine(P1, Width - 22, 0, Width - 22, Height); G.DrawLine(P4, Width - 23, 1, Width - 23, Height - 2); G.DrawLine(P4, Width - 21, 1, Width - 21, Height - 2); }
/// <summary> /// Draw the specified text to a fixed-sized Bitmap /// (text/font will be sized to fit the specified dimensions) /// </summary> /// <param name="text">The text to draw.</param> /// <param name="fontName">The name of the font to use.</param> /// <param name="width">The width of the resulting <see cref="Bitmap"/></param> /// <param name="height">The height of the resulting <see cref="Bitmap"/></param> /// <param name="fontStyle">the <paramref name="fontStyle"/> to use.</param> /// <param name="bgColor">The background <see cref="Color"/> to draw to the result</param> /// <param name="fgColor">The foreground <see cref="Color"/> to draw the text with.</param> /// <returns>A Bitmap</returns> /// <remarks>Can be used as an extension method.</remarks> public static Bitmap DrawTextToFixedBitmap( this string text, string fontName, int width = 64, int height = 64, FontStyle fontStyle = FontStyle.Regular, Color?bgColor = null, Color?fgColor = null) { if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentNullException(nameof(text)); } if (string.IsNullOrWhiteSpace(fontName)) { fontName = TextToBmpOptions.MDL2_FONT_NAME; } if (width < MinimumFontSize) { throw new ArgumentOutOfRangeException(nameof(width)); } if (height < MinimumFontSize) { throw new ArgumentOutOfRangeException(nameof(height)); } // Do NOT "using" the result, or the bitmap will be disposed when the method returns. Bitmap res = new Bitmap(width, height); using (Graphics gr = Graphics.FromImage(res)) { if (bgColor.HasValue && bgColor != transparent) { gr.FillRectangle(new SolidBrush(bgColor.Value), 0, 0, width, height); } int fontSize = height; bool tooBig = true; while (tooBig && fontSize > MinimumFontSize) { if (fontSize < MinimumFontSize) { throw new Exception($"The text will not fit in the size specified [{width} x {height}]."); } using (Font font = new Font(fontName, fontSize, fontStyle)) { SizeF size = gr.MeasureString(text, font); tooBig = size.Width > width || size.Height > height; if (!tooBig) { // Center text float fW = (width - size.Width) > 0 ? (width - size.Width) / 2 : 0; float fH = (height - size.Height) > 0 ? (height - size.Height) / 2 : 0; gr.DrawString(text, font, new SolidBrush(fgColor ?? black), fW, fH); gr.Flush(); return(res); } else { fontSize--; } } } } throw new Exception($"The text will not fit in the size specified [{width} x {height}]."); }
///<summary>Prints one page. Returns true if pageToPrint is the last page in this print job.</summary> private bool Print(Graphics g, int pageToPrint, Rectangle margins) { //Messages may span multiple pages. We print the header on each page as well as the page number. float baseY = margins.Top; string text = "Page " + (pageToPrint + 1); Font font = Font; SizeF textSize = g.MeasureString(text, font); g.DrawString(text, font, Brushes.Black, margins.Right - textSize.Width, baseY); baseY += textSize.Height; text = Text; font = new Font(Font.FontFamily, 16, FontStyle.Bold); textSize = g.MeasureString(text, font); g.DrawString(text, font, Brushes.Black, (margins.Width - textSize.Width) / 2, baseY); baseY += textSize.Height; font.Dispose(); font = new Font(Font.FontFamily, 14, FontStyle.Bold); text = DateTime.Now.ToString(); textSize = g.MeasureString(text, font); g.DrawString(text, font, Brushes.Black, (margins.Width - textSize.Width) / 2, baseY); baseY += textSize.Height; font.Dispose(); string[] messageLines = textMain.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); font = Font; bool isLastPage = false; float y = 0; for (int curPage = 0, msgLine = 0; curPage <= pageToPrint; curPage++) { //Set y to its initial value for the current page (right after the header). y = curPage * (margins.Bottom - baseY); while (msgLine < messageLines.Length) { //If a line is blank, we need to make sure that is counts for some vertical space. if (messageLines[msgLine] == "") { textSize = g.MeasureString("A", font); } else { textSize = g.MeasureString(messageLines[msgLine], font); } //Would the current text line go past the bottom margin? if (y + textSize.Height > (curPage + 1) * (margins.Bottom - baseY)) { break; } if (curPage == pageToPrint) { g.DrawString(messageLines[msgLine], font, Brushes.Black, margins.Left, baseY + y - curPage * (margins.Bottom - baseY)); if (msgLine == messageLines.Length - 1) { isLastPage = true; } } y += textSize.Height; msgLine++; } } return(isLastPage); }
public void PrintPage(PrintPageEventArgs e) { float pagewidth = e.MarginBounds.Width * 3.0f; float pageheight = e.MarginBounds.Height * 3.0f; float textwidth = 0.0f; float textheight = 0.0f; float offsetx = e.MarginBounds.Left * 3.0f; float offsety = e.MarginBounds.Top * 3.0f; float x = offsetx; float y = offsety; StringBuilder line = new StringBuilder(256); StringFormat sf = StringFormat.GenericTypographic; sf.FormatFlags = StringFormatFlags.DisplayFormatControl; sf.SetTabStops(0.0f, new float[] { 300.0f }); RectangleF r; Graphics g = e.Graphics; g.PageUnit = GraphicsUnit.Document; SizeF size = g.MeasureString("X", font, 1, sf); float lineheight = size.Height; // make sure we can print at least 1 line (font too big?) if (lineheight + (lineheight * 3) > pageheight) { // cannot print at least 1 line and footer g.Dispose(); e.HasMorePages = false; return; } // don't include footer pageheight -= lineheight * 3; // last whitespace in line buffer int lastws = -1; // next character int c; for (;;) { // get next character c = NextChar(); // append c to line if not NewLine or Eos if ((c != NewLine) && (c != Eos)) { Char ch = Convert.ToChar(c); line.Append(ch); // if ch is whitespace, remember pos and continue if (ch == ' ' || ch == '\t') { lastws = line.Length - 1; continue; } } // measure string if line is not empty if (line.Length > 0) { size = g.MeasureString(line.ToString(), font, int.MaxValue, StringFormat.GenericTypographic); textwidth = size.Width; } // draw line if line is full, if NewLine or if last line if (c == Eos || (textwidth > pagewidth) || (c == NewLine)) { if (textwidth > pagewidth) { if (lastws != -1) { offset -= line.Length - lastws - 1; line.Length = lastws + 1; } else { line.Length--; offset--; } } // there's something to draw if (line.Length > 0) { r = new RectangleF(x, y, pagewidth, lineheight); sf.Alignment = StringAlignment.Near; g.DrawString(line.ToString(), font, Brushes.Black, r, sf); } // increase ypos y += lineheight; textheight += lineheight; // empty line buffer line.Length = 0; textwidth = 0.0f; lastws = -1; } // if next line doesn't fit on page anymore, exit loop if (textheight > (pageheight - lineheight) || c == Eos) { break; } } // print footer x = offsetx; y = offsety + pageheight + (lineheight * 2); r = new RectangleF(x, y, pagewidth, lineheight); sf.Alignment = StringAlignment.Center; g.DrawString(page.ToString(), font, Brushes.Black, r, sf); g.Dispose(); page++; e.HasMorePages = c != Eos; }
public OkCancel(string q = "question for OkCancel window") { // Text = q; MinimizeBox = false; MaximizeBox = false; ControlBox = false; AutoScroll = false; // FormBorderStyle = FormBorderStyle.FixedDialog; // AutoSize = true; // _pd = new Padding(SZ.X_SPC, SZ.Y_SPC, SZ.X_SPC, 0); // _pd = new Padding(1); Graphics g = CreateGraphics(); StringFormat sf = new StringFormat(StringFormatFlags.DirectionVertical); sizef = g.MeasureString(q, this.Font, Int32.MaxValue, sf); DialogResult = DialogResult.Cancel; bSz = new System.Drawing.Size(ut.SZ.X_BUTTON + 30, ut.SZ.Y + 10); OK_but = new _Button(); OK_but.Name = "OK_but"; OK_but.Text = CNST.BTTN_OK; OK_but.DialogResult = DialogResult.OK; OK_but.Click += new System.EventHandler(_OK_but); ESC_but = new _Button(); ESC_but.Name = "ESC_but"; ESC_but.Size = bSz; ESC_but.Text = CNST.BTTN_ESC; ESC_but.DialogResult = DialogResult.Cancel; /// #if LAYOUT tPL = new TableLayoutPanel(); tPL.ColumnCount = 4; // две колонки; tPL.RowCount = 1; tPL.Padding = _pd; tPL.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset; tPL.AutoSize = true; #endif // ////if (Size.Width < sizef.Width+SZ.X_SPC*2 ) //// ClientSize = new Size((int)(sizef.Width+SZ.X_SPC*2), Size.Height); ///// this.MinimumSize = Size; /// // this.AcceptButton = OK_but; // нажатие ентера как на ок // this.CancelButton = ESC_but; //нажатие esc // ESC_but.Dock = DockStyle.Fill; // ESC_but.Dock = DockStyle.Left; // x , y // OK_but.Dock = DockStyle.Left; // #if PANEL Panel p = new Panel(); Panel p1 = new Panel(); #else Button p1 = new Button(); Button p = new Button(); #endif p.Size = bSz; p1.Size = bSz; #if LAYOUT tPL.Controls.Add(OK_but, 0, 0); tPL.Controls.Add(p, 1, 0); // tPL.Controls.Add(p1, 2, 0); tPL.Controls.Add(ESC_but, 3, 0); Controls.Add(tPL); ClientSize = tPL.Size; OK_but.Size = bSz; ESC_but.Size = bSz; // tPL.Size = new Size(tPL.Size.Width, ytab(ySize = 1) + SZ.Y_SPC * 2); #else Controls.Add(OK_but); OK_but.Dock = DockStyle.Left; Controls.Add(p); Controls.Add(p1); Controls.Add(ESC_but); ESC_but.Dock = DockStyle.Right; #endif Location = new System.Drawing.Point(ut.SZ.X_SPC, ut.SZ.Y_SPC); }
private Size GetTextSize(Graphics graphics) { SizeF size = graphics.MeasureString(String.Format("{0}", 0), hudFont); return(new Size((int)size.Width, (int)size.Height)); }
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { e.HasMorePages = false; float x = 10; float y = 10; int imgWidth = 200; int imgHeight = 200; string ordID = "Order id : " + Bestellingen.orderline.orderid.ToString(); string klant = "Klant : " + cmbKlanten.SelectedItem.ToString(); string date = "Datum : " + DateTime.UtcNow.ToString(); Pen p = new Pen(Color.Black, 1); Font f = new Font("Arial", 16, FontStyle.Bold); Font f1 = new Font("Arial", 14, FontStyle.Bold); Font f2 = new Font("Arial", 12, FontStyle.Bold); SizeF strSizeInvNum = e.Graphics.MeasureString(ordID, f); SizeF strSizeDate = e.Graphics.MeasureString(date, f); SizeF strSizeName = e.Graphics.MeasureString(klant, f); e.Graphics.DrawImage(Image.FromFile(Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.Length - 9) + "Resources\\download.jpg"), x, y, imgWidth, imgHeight); e.Graphics.DrawString(ordID, f, Brushes.DarkBlue, imgWidth + x, y); e.Graphics.DrawString(date, f, Brushes.DarkBlue, imgWidth + x, y + imgHeight / 2); e.Graphics.DrawString(klant, f, Brushes.DarkBlue, imgWidth + x, y + strSizeInvNum.Height + strSizeDate.Height * 4); float preHeight = strSizeInvNum.Height + strSizeDate.Height + strSizeName.Height + imgHeight + y; e.Graphics.DrawRectangle(p, x, imgHeight + y * 2, e.PageBounds.Width - x * 2, e.PageBounds.Height - preHeight); float colHeight = 60; float col1Width = 180; float col2Width = 200 + col1Width; float col3Width = 75 + col2Width; float col4Width = 80 + col3Width; float col5Width = 60 + col4Width; float col6Width = 80 + col5Width; e.Graphics.DrawLine(p, x, preHeight, e.PageBounds.Width - x, preHeight); e.Graphics.DrawString("Product", f, Brushes.DarkBlue, x * 2, preHeight - colHeight); e.Graphics.DrawLine(p, x * 2 + col1Width, imgHeight + y * 2, x * 2 + col1Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Omschrijving", f, Brushes.DarkBlue, x * 2 + col1Width, preHeight - colHeight); e.Graphics.DrawLine(p, x * 2 + col2Width, imgHeight + y * 2, x * 2 + col2Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Prijs", f, Brushes.DarkBlue, x * 2 + col2Width, preHeight - colHeight); e.Graphics.DrawLine(p, x * 2 + col3Width, imgHeight + y * 2, x * 2 + col3Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Prijs (btw)", f2, Brushes.DarkBlue, x * 2 + col3Width, preHeight - colHeight + 3); e.Graphics.DrawLine(p, x * 2 + col4Width, imgHeight + y * 2, x * 2 + col4Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Qtt", f, Brushes.DarkBlue, x * 2 + col4Width, preHeight - colHeight); e.Graphics.DrawLine(p, x * 2 + col5Width, imgHeight + y * 2, x * 2 + col5Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Totaal", f, Brushes.DarkBlue, x * 2 + col5Width, preHeight - colHeight); e.Graphics.DrawLine(p, x * 2 + col6Width, imgHeight + y * 2, x * 2 + col6Width, e.PageBounds.Height - colHeight - y * 4); e.Graphics.DrawString("Totaal (btw)", f2, Brushes.DarkBlue, x * 2 + col6Width, preHeight - colHeight + 3); e.Graphics.DrawLine(p, x * 2 + col6Width, imgHeight + y * 2, x * 2 + col6Width, e.PageBounds.Height - colHeight - y * 4); float rowHeight = 60; double totaal = 0; for (int i = 0; i < dgvOrderProducten.Rows.Count; i++) { totaal += (Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[7].Value) * Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[5].Value)); } for (int i = 0; i < dgvOrderProducten.Rows.Count; i++) { if (rowHeight >= e.PageBounds.Height - preHeight - colHeight) { e.HasMorePages = true; break; } e.Graphics.DrawString(dgvOrderProducten.Rows[i].Cells[3].Value.ToString(), f2, Brushes.DarkBlue, x * 2, preHeight + rowHeight - colHeight); e.Graphics.DrawString(dgvOrderProducten.Rows[i].Cells[6].Value.ToString(), f2, Brushes.DarkBlue, x * 2 + col1Width, preHeight + rowHeight - colHeight); e.Graphics.DrawString(Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[5].Value).ToString("0.##"), f2, Brushes.DarkBlue, x * 2 + col2Width, preHeight + rowHeight - colHeight); e.Graphics.DrawString((Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[5].Value) * 1.21).ToString("0.##"), f2, Brushes.DarkBlue, x * 2 + col3Width, preHeight + rowHeight - colHeight); e.Graphics.DrawString(dgvOrderProducten.Rows[i].Cells[7].Value.ToString(), f2, Brushes.DarkBlue, x * 2 + col4Width, preHeight + rowHeight - colHeight); e.Graphics.DrawString((Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[7].Value) * Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[5].Value)).ToString("0.##"), f2, Brushes.DarkBlue, x * 2 + col5Width, preHeight + rowHeight - colHeight); e.Graphics.DrawString((Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[7].Value) * Convert.ToDouble(dgvOrderProducten.Rows[i].Cells[5].Value) * 1.21).ToString("0.##"), f2, Brushes.DarkBlue, x * 2 + col6Width, preHeight + rowHeight - colHeight); e.Graphics.DrawLine(p, x, preHeight + rowHeight, e.PageBounds.Width - x, preHeight + rowHeight); rowHeight += 60; } if (rowHeight < e.PageBounds.Height - preHeight - colHeight) { e.Graphics.DrawString("Totaal zonder btw : " + totaal.ToString("0.##"), f, Brushes.Red, e.PageBounds.Width / 2, preHeight + rowHeight - colHeight); e.Graphics.DrawLine(p, x, preHeight + rowHeight, e.PageBounds.Width - x, preHeight + rowHeight + 40); e.Graphics.DrawString("Totaal inclusief btw : " + (totaal * 1.21).ToString("0.##"), f, Brushes.Red, e.PageBounds.Width / 2, preHeight + rowHeight + 40 - colHeight); } }
public Glyph(char glyphChar, SizeF glyphSize, int elementIndex) : base(glyphChar, glyphSize) { ElementIndex = elementIndex; }
private static PointF Mod(PointF p, SizeF s) { return(new PointF(Mod(p.X, s.Width), Mod(p.Y, s.Height))); }
///<summary>Draws the number and the rectangle behind it. Draws in the appropriate color</summary> private void DrawNumber(string tooth_id, bool isSelected, bool isFullRedraw, Graphics g) { if (DesignMode) { return; } if (TcData == null) { return; //trying to fix a designtime bug. } if (!Tooth.IsValidDB(tooth_id)) { return; } if (TcData.ListToothGraphics[tooth_id] == null) { //throw new Exception(tooth_id+" null"); return; //for some reason, it's still getting to here in DesignMode } if (isFullRedraw) //if redrawing all numbers { if (TcData.ListToothGraphics[tooth_id].HideNumber) //and this is a "hidden" number { return; //skip } if (Tooth.IsPrimary(tooth_id) && !TcData.ListToothGraphics[Tooth.PriToPerm(tooth_id)].ShowPrimaryLetter) //but not set to show primary letters { return; } } string displayNum = Tooth.GetToothLabelGraphic(tooth_id, TcData.ToothNumberingNomenclature); float toMm = 1f / TcData.ScaleMmToPix; float labelWidthMm = g.MeasureString(displayNum, Font).Width / TcData.ScaleMmToPix; float labelHeightMm = ((float)Font.Height - .5f) / TcData.ScaleMmToPix; SizeF labelSizeF = new SizeF(labelWidthMm, (float)Font.Height / TcData.ScaleMmToPix); Rectangle rec = TcData.GetNumberRecPix(tooth_id, labelSizeF); //Rectangle recPix=TcData.ConvertRecToPix(recMm); if (isSelected) { g.FillRectangle(new SolidBrush(TcData.ColorBackHighlight), rec); } else { g.FillRectangle(new SolidBrush(TcData.ColorBackground), rec); } if (TcData.ListToothGraphics[tooth_id].HideNumber) //If number is hidden. //do not print string { } else if (Tooth.IsPrimary(tooth_id) && !TcData.ListToothGraphics[Tooth.PriToPerm(tooth_id)].ShowPrimaryLetter) { //do not print string } else if (isSelected) { g.DrawString(displayNum, Font, new SolidBrush(TcData.ColorTextHighlight), rec.X, rec.Y); } else { g.DrawString(displayNum, Font, new SolidBrush(TcData.ColorText), rec.X, rec.Y); } }
private SizeF NativeMeasureContent(SizeF availableSize) { return(new SizeF()); }
public bool ConvertBoardFile(string SourceFilename, string OutputFolder, string ProjectName) { bool result = false; int net_index = 1; DesignRules designRules = new DesignRules(); PartMap = new RenameMap(); k.LayerDescriptor layer; Trace(string.Format("Reading board file {0}", SourceFilename)); board = EagleFile.LoadFromXmlFile(SourceFilename); // if (board != null) { libraryConverter = new LibraryConverter(Parent); ConvertComponentLibraries(OutputFolder, false); k.Pcb.kicad_pcb k_pcb = new k.Pcb.kicad_pcb(); k_pcb.Modules = new List <k.ModuleDef.Module>(); k_pcb.Drawings = new List <k.Pcb.graphic_base>(); // paper and size: get the page size PageStr = "A4"; PageSize = new SizeF(297, 210); foreach (Element element in board.Drawing.Board.Elements.Element) { // if (element.Library == "frames") { //todo: //ConvertFrame(element.Package); break; } } k_pcb.Page = PageStr; // offset from bottom left DrawingOffset = new PointF(2 * Common.inch_to_mm, 2 * Common.inch_to_mm); k_pcb.Setup.grid_origin = StrToPoint_Board("0", "0"); //testFont(k_pcb); // ** debug // get list of part names foreach (Element element in board.Drawing.Board.Elements.Element) { PartMap.Add(element.Name); } PartMap.Annotate(); // layers? #region ==== designrules ==== foreach (Param param in board.Drawing.Board.Designrules.Param) { designRules.Add(param.Name, param.Value); } #endregion #region ==== Plain - text ==== foreach (Text text in board.Drawing.Board.Plain.Text) { bool mirror; int angle = Common.xGetAngleFlip(text.Rot, out mirror); layer = ConvertLayer(text.Layer); if (layer != null) { k.Pcb.gr_text k_text = new k.Pcb.gr_text( text.mText, StrToPoint_Board(text.X, text.Y), layer.Name, new SizeF(Common.StrToVal_mm(text.Size), Common.StrToVal_mm(text.Size)), Common.GetTextThickness_mm(text), angle ); k_text.effects.horiz_align = k.TextJustify.left; SizeF textSize = strokeFont.GetTextSize(text.mText, k_text.effects); PointF offset = new PointF(textSize.Width / 2, textSize.Height / 2); // TODO: spin switch ((int)ExtRotation.Parse(text.Rot).Rotation) { case 0: if (mirror) { k_text.Position.At.Y -= offset.Y; } else { k_text.Position.At.Y -= offset.Y; } break; case 90: if (mirror) { k_text.Position.At.X += offset.Y; k_text.Position.At.Y -= textSize.Width; } else { k_text.Position.At.X -= offset.Y; } break; case 180: if (mirror) { k_text.Position.At.Y += offset.Y; } else { k_text.Position.At.Y += textSize.Height; } break; case 270: if (mirror) { k_text.Position.At.X -= offset.Y; k_text.Position.At.Y += textSize.Width; } else { k_text.Position.At.X += offset.Y; } break; } k_pcb.Drawings.Add(k_text); } } #endregion #region ==== Plain - lines ==== foreach (Wire wire in board.Drawing.Board.Plain.Wire) { layer = ConvertLayer(wire.Layer); if (layer != null) { float width = Common.StrToVal_mm(wire.Width); //todo: arcs k.Pcb.gr_line k_line = new k.Pcb.gr_line( StrToPoint_Board(wire.X1, wire.Y1), StrToPoint_Board(wire.X2, wire.Y2), layer.Name, width ); k_pcb.Drawings.Add(k_line); } } #endregion #region ==== Plain - rectangle ==== // convert to unconnected zones foreach (EagleImport.Rectangle rect in board.Drawing.Board.Plain.Rectangle) { layer = ConvertLayer(rect.Layer); if (layer != null) { PointF p1 = StrToPoint_Board(rect.X1, rect.Y1); PointF p2 = StrToPoint_Board(rect.X2, rect.Y2); k.Pcb.Zone zone = new k.Pcb.Zone(); zone.layer = layer.Name; zone.net = 0; zone.net_name = ""; zone.hatch_pitch = 0.508f; zone.connect_pads_clearance = 0.508f; zone.min_thickness = 0.001f; zone.is_filled = false; zone.fill_arc_segments = 16; zone.fill_thermal_gap = 0.508f; zone.fill_thermal_bridge_width = 0.508f; zone.polygon.Add(new PointF(p1.X, p1.Y)); zone.polygon.Add(new PointF(p2.X, p1.Y)); zone.polygon.Add(new PointF(p2.X, p2.Y)); zone.polygon.Add(new PointF(p1.X, p2.Y)); k_pcb.Zones.Add(zone); // todo : not needed? //k.Pcb.gr_line k_line; //k_line = new k.Pcb.gr_line(new PointF(p1.X, p1.Y), new PointF(p2.X, p1.Y), layer.Name, width); //k_pcb.Drawings.Add(k_line); //k_line = new k.Pcb.gr_line(new PointF(p2.X, p1.Y), new PointF(p2.X, p2.Y), layer.Name, width); //k_pcb.Drawings.Add(k_line); //k_line = new k.Pcb.gr_line(new PointF(p1.X, p2.Y), new PointF(p2.X, p2.Y), layer.Name, width); //k_pcb.Drawings.Add(k_line); //k_line = new k.Pcb.gr_line(new PointF(p1.X, p1.Y), new PointF(p1.X, p2.Y), layer.Name, width); //k_pcb.Drawings.Add(k_line); } } #endregion #region ==== Plain - Hole ==== foreach (Hole hole in board.Drawing.Board.Plain.Hole) { PointF p1 = StrToPoint_Board(hole.X, hole.Y); float drill = Common.StrToVal_mm(hole.Drill); k_pcb.AddModule(NonplatedHole(drill, drill), p1); } #endregion #region ==== plain.dimension ==== foreach (Dimension dim in board.Drawing.Board.Plain.Dimension) { layer = ConvertLayer(dim.Layer); if (layer != null) { PointF p1 = StrToPoint_Board(dim.X1, dim.Y1); PointF p2 = StrToPoint_Board(dim.X2, dim.Y2); PointF p3 = StrToPoint_Board(dim.X3, dim.Y3); float line_width = 0.15f; // default width? float text_size = Common.StrToVal_mm(dim.TextSize); float text_width = Common.GetTextThickness_mm(dim.TextSize, dim.TextRatio); if (!string.IsNullOrEmpty(dim.Width)) { line_width = Common.StrToVal_mm(dim.Width); } switch (dim.Dtype) { case DimensionType.parallel: case DimensionType.radius: case DimensionType.diameter: k.Pcb.Dimension k_dim = new k.Pcb.Dimension(layer.Name, line_width, p1, p2, text_size, text_width, dim.Unit == GridUnit.mm, int.Parse(dim.Precision), dim.Visible == Bool.yes); k_pcb.Dimensions.Add(k_dim); break; //todo : others? } } } #endregion #region ==== plain.polygon ==== foreach (EagleImport.Polygon poly in board.Drawing.Board.Plain.Polygon) { //todo // if layer is tRestrict or bRestrict, create a keepout zone if ((poly.Layer == "41") || (poly.Layer == "42")) { k.Pcb.Zone zone = new k.Pcb.Zone(); if (poly.Layer == "41") { zone.layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nFront_Cu); } else if (poly.Layer == "42") { zone.layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nBack_Cu); } zone.net = 0; zone.net_name = ""; zone.hatch_pitch = 0.508f; zone.connect_pads_clearance = 0; zone.min_thickness = 10.0f; zone.is_filled = false; zone.fill_arc_segments = 16; zone.connect_pads_mode = k.Pcb.ZonePadConnection.yes; //solid zone.fill_thermal_gap = 0.508f; zone.fill_thermal_bridge_width = 0.508f; zone.is_keepout = true; zone.outline_style = k.Pcb.ZoneOutlineStyle.none; zone.keepout_allow_copper_pour = Kicad_utils.Allowed.not_allowed; zone.priority = 7; foreach (Vertex v in poly.Vertex) { zone.polygon.Add(StrToPoint_Board(v.X, v.Y)); } k_pcb.Zones.Add(zone); } } #endregion #region ==== Signals ==== // get net list foreach (Signal signal in board.Drawing.Board.Signals.Signal) { //todo: ? k_pcb.Nets.Add(new k.Pcb.Net(net_index, signal.Name)); net_index++; } List <PinConnection> Contacts = new List <PinConnection>(); foreach (Signal signal in board.Drawing.Board.Signals.Signal) { //todo: ? k.Pcb.Net k_net = k_pcb.Nets.Find(x => x.Name == signal.Name); foreach (Wire wire in signal.Wire) { layer = ConvertLayer(wire.Layer); if (layer != null) { // todo: segment must be on a copper layer? // ignore unrouted if (wire.Layer != "19") { float width = Common.StrToVal_mm(wire.Width); //todo: arcs? k.Pcb.PcbSegment seg = new Kicad_utils.Pcb.PcbSegment(); seg.layer = layer.Name; seg.net = k_net.Number; seg.start = StrToPoint_Board(wire.X1, wire.Y1); seg.end = StrToPoint_Board(wire.X2, wire.Y2); seg.width = width; k_pcb.Segments.Add(seg); Contacts.Add(new PinConnection(signal.Name, seg.start, layer.Name, null, null)); Contacts.Add(new PinConnection(signal.Name, seg.end, layer.Name, null, null)); } } } // contactref foreach (Contactref con_ref in signal.Contactref) { Contacts.Add(new PinConnection(signal.Name, PointF.Empty, null, con_ref.Element, con_ref.Pad)); } //<via x="6.6675" y="49.2125" extent="1-16" drill="0.3" shape="octagon"/> foreach (Via via in signal.Via) { float drill = Common.StrToVal_mm(via.Drill); PointF pos = StrToPoint_Board(via.X, via.Y); float size = Common.StrToVal_mm(via.Diameter); if (size == 0) { size = designRules.CalcViaSize(drill); } k.Pcb.Via k_via = new k.Pcb.Via(pos, size, drill, k.LayerList.StandardLayers.GetLayerName(k.Layer.nFront_Cu), k.LayerList.StandardLayers.GetLayerName(k.Layer.nBack_Cu), k_net.Number); PinConnection p_conn = Contacts.Find(x => x.position.X == k_via.at.X && x.position.Y == k_via.at.Y); if (via.Extent == "1-16") { k_via.topmost_layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nFront_Cu); k_via.backmost_layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nBack_Cu); } else { Trace(string.Format("error : blind/buried via ? {0},{1} {2} {3}", via.X, via.Y, signal.Name, via.Extent)); } if (p_conn == null) { Trace(string.Format("note : loose via converted to pad at {0},{1} net={2}", via.X, via.Y, signal.Name)); k.ModuleDef.Module k_pad = ViaPad(size, drill, k_net); k_pcb.AddModule(k_pad, pos); } else { k_pcb.Vias.Add(k_via); } } foreach (EagleImport.Polygon poly in signal.Polygon) { //<polygon width="0.2032" layer="1" spacing="0.254" isolate="0.254" rank="2"> //defaults are 6 mil float width = 0.1524f; float isolate = 0.1524f; float spacing = 0.1524f; int rank = int.Parse(poly.Rank); layer = ConvertLayer(poly.Layer); if (layer != null) { //todo: clearances etc should come from DesignRules? if (!string.IsNullOrEmpty(poly.Width)) { width = Common.StrToVal_mm(poly.Width); } if (!string.IsNullOrEmpty(poly.Isolate)) { isolate = Common.StrToVal_mm(poly.Isolate); } if (!string.IsNullOrEmpty(poly.Spacing)) { spacing = Common.StrToVal_mm(poly.Spacing); } if (k.Layer.IsCopperLayer(layer.Number) || (poly.Layer == "41") || (poly.Layer == "42")) { k.Pcb.Zone zone = new k.Pcb.Zone(); if (poly.Layer == "41") { zone.layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nFront_Cu); } else if (poly.Layer == "42") { zone.layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nBack_Cu); } else { zone.layer = layer.Name; } zone.net = k_net.Number; zone.net_name = k_net.Name; zone.outline_style = k.Pcb.ZoneOutlineStyle.edge; zone.hatch_pitch = 0.508f; zone.connect_pads_clearance = 0.2032f; zone.min_thickness = width; // ?? zone.fill_arc_segments = 32; zone.fill_thermal_gap = 0.2032f; zone.fill_thermal_bridge_width = 0.2032f; zone.is_filled = false; foreach (Vertex v in poly.Vertex) { zone.polygon.Add(StrToPoint_Board(v.X, v.Y)); } if ((poly.Pour == PolygonPour.cutout) || !k.Layer.IsCopperLayer(layer.Number)) { zone.is_keepout = true; zone.outline_style = k.Pcb.ZoneOutlineStyle.none; zone.keepout_allow_copper_pour = Kicad_utils.Allowed.not_allowed; } if (!string.IsNullOrEmpty(poly.Isolate)) { zone.connect_pads_clearance = isolate; } if (poly.Thermals == Bool.yes) { zone.connect_pads_mode = k.Pcb.ZonePadConnection.thermal_relief; zone.fill_thermal_gap = width + 0.001f; // ** zone.fill_thermal_bridge_width = width + 0.001f; // ** } else { zone.connect_pads_mode = k.Pcb.ZonePadConnection.yes; } // priority on KiCad is opposite to rank zone.priority = 6 - rank; k_pcb.Zones.Add(zone); } } } // } #endregion #region ==== Elements ==== foreach (Element element in board.Drawing.Board.Elements.Element) { //todo: k.ModuleDef.Module k_mod; // find package library : package string footprint_sid = element.Library + ":" + libraryConverter.FootprintNameMap.GetNewName(element.Package); k.ModuleDef.Module k_template = libraryConverter.AllFootprints.Find(x => x.Name == footprint_sid); if (k_template == null) { Trace(string.Format("error: {0} not found", footprint_sid)); } else { k_mod = k_template.Clone(true); k_mod.Name = footprint_sid; k_mod.Reference.Value = PartMap.GetNewName(element.Name); k_mod.At = StrToPoint_Board(element.X, element.Y); if (k_mod.Value != null) { k_mod.Value.Value = element.Value; } k_mod.layer = k.LayerList.StandardLayers.GetLayerName(k.Layer.nFront_Cu); // Set position, orientation ExtRotation elementRot = ExtRotation.Parse(element.Rot); int element_angle = (int)elementRot.Rotation; // get attributes for text foreach (EagleImport.Attribute attrib in element.Attribute) { ExtRotation attrRot = ExtRotation.Parse(attrib.Rot); bool attr_mirror = attrRot.Mirror; int attr_angle = (int)attrRot.Rotation; layer = ConvertLayer(attrib.Layer); if (layer != null) { //k.Symbol.SymbolField sym_field = null; k.ModuleDef.fp_text field = null; switch (attrib.Name) { case "NAME": //sym_field = k_symbol.fReference; field = k_mod.Reference; break; case "VALUE": //sym_field = k_symbol.fValue; field = k_mod.Value; break; // Part? // voltage, current } if (field != null) { field.effects.font.Size = new SizeF(Common.StrToVal_mm(attrib.Size), Common.StrToVal_mm(attrib.Size)); field.layer = layer.Name; field.layer = k.Layer.MakeLayerName(k_mod.layer, field.layer); //field.effects.horiz_align = k.TextJustify.left; //field.effects.vert_align = k.VerticalAlign.bottom; SetPcbTextAttributes(field, StrToPoint_Board(element.X, element.Y), elementRot, StrToPoint_Board(attrib.X, attrib.Y), attrRot); // AdjustPos(field); //debug if (pcb_debug) { PointF ptext = new PointF(field.position.At.X, field.position.At.Y); SizeF textSize = strokeFont.GetTextSize(field.Value, field.effects); if (elementRot.Mirror) { // get bottom right ptext.X += textSize.Width / 2; ptext.Y += textSize.Height / 2; ptext = ptext.Rotate(-elementRot.Rotation - 180); ptext.Y = -ptext.Y; } else { // get bottom left ptext.X -= textSize.Width / 2; ptext.Y += textSize.Height / 2; ptext = ptext.Rotate(-elementRot.Rotation); } ptext = k_mod.position.At.Add(ptext); //!DrawRect(k_pcb, ptext, textSize, -(elementRot.Rotation + field.position.Rotation)); // PointF p1 = new PointF(field.position.At.X, field.position.At.Y); k.Pcb.gr_line k_line; float ds = 1.27f; if (elementRot.Mirror) { p1 = p1.Rotate(-elementRot.Rotation - 180); p1.Y = -p1.Y; } else { p1 = p1.Rotate(-elementRot.Rotation); } //p1 = p1.Rotate(field.position.Rotation); //p1 = p1.Rotate(k_mod.position.Rotation); k_line = new k.Pcb.gr_line( new PointF(k_mod.position.At.X + p1.X - ds, k_mod.position.At.Y + p1.Y), new PointF(k_mod.position.At.X + p1.X + ds, k_mod.position.At.Y + p1.Y), "Dwgs.User", 0.01f); k_pcb.Drawings.Add(k_line); k_line = new k.Pcb.gr_line( new PointF(k_mod.position.At.X + p1.X, k_mod.position.At.Y + p1.Y - ds), new PointF(k_mod.position.At.X + p1.X, k_mod.position.At.Y + p1.Y + ds), "Dwgs.User", 0.01f); k_pcb.Drawings.Add(k_line); } } } } // Note: the Eagle "mirror" attribute reverses side and flips about Y | axis, but // Kicad "flip" reverses side and flips about X -- axis. // therefore Eagle mirror is equivalent to Kicad flip + rotate(180) if (elementRot.Mirror) { k_mod.RotateBy(MathUtil.NormalizeAngle(-(element_angle + 180))); k_mod.FlipX(k_mod.position.At); } else //if (element_angle != 0) { k_mod.RotateBy(element_angle); } // fix up pads foreach (k.ModuleDef.pad pad in k_mod.Pads) { string new_name = PartMap.GetNewName(element.Name); if (pad.type != k.ModuleDef.pad.nonplated_hole) { PinConnection contact = Contacts.Find(x => x.PartName == element.Name && x.PinName == pad.number); if (contact == null) { // may actually be a non-connect // Trace(string.Format("warning: contact {0} {1} not found", element.Name, pad.number)); } else { pad.net = k_pcb.Nets.Find(x => x.Name == contact.NetLabel); } } } // k_pcb.Modules.Add(k_mod); } } #endregion // transfer some design rules k_pcb.Setup.trace_min = designRules.GetValueFloat("msWidth"); k_pcb.Setup.via_min_size = designRules.GetValueFloat("msWidth"); k_pcb.Setup.via_min_drill = designRules.GetValueFloat("msDrill"); k_pcb.Setup.uvia_min_size = designRules.GetValueFloat("msMicroVia"); k_pcb.Setup.uvia_min_drill = designRules.GetValueFloat("msMicroVia"); // not right, but need layer thickness to calculate correctly // allow uvia // allow blind/buried via // grid // text and drawings // pad // pad mask clearance //default netclass k_pcb.NetClasses[0].clearance = designRules.GetValueFloat("mdPadVia"); k_pcb.NetClasses[0].trace_width = designRules.GetValueFloat("msWidth"); k_pcb.NetClasses[0].via_dia = designRules.GetValueFloat("msWidth"); k_pcb.NetClasses[0].via_drill = designRules.GetValueFloat("msDrill"); k_pcb.NetClasses[0].uvia_dia = designRules.GetValueFloat("msMicroVia"); k_pcb.NetClasses[0].uvia_drill = designRules.GetValueFloat("msMicroVia"); // not right // write the KiCad file string filename = Path.Combine(OutputFolder, ProjectName + ".kicad_pcb"); Trace(string.Format("Writing board {0}", filename)); k_pcb.SaveToFile(filename); result = true; } else { result = false; Trace(string.Format("error opening {0}", SourceFilename)); } return(result); }
/// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.Paint" /> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs" /> that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { IEnumerator <ZeroitMetroTaskPoint> enumerator = this._PointCollection.GetEnumerator(); Rectangle rectangle; Rectangle rectangle1 = new Rectangle(); Graphics graphics = e.Graphics; if (AllowTransparency) { MakeTransparent(this, graphics); } graphics.SmoothingMode = SmoothingMode.AntiAlias; int circleWidth = this._StartPointWidth; Point point = new Point(checked (circleWidth + 6), checked (circleWidth + 6)); Point point1 = new Point(checked (circleWidth + 6), checked (this.Height - (checked (circleWidth + 6)))); this._PointPosition.Clear(); this._TextRectangles.Clear(); if (this._PointCollection.Count > 0) { while (enumerator.MoveNext()) { ZeroitMetroTaskPoint current = enumerator.Current; if (current.CircleWidth > circleWidth) { circleWidth = current.CircleWidth; } } point = new Point(checked (circleWidth + 6), checked (circleWidth + 6)); point1 = new Point(checked (circleWidth + 6), checked (this.Height - (checked (circleWidth + 6)))); this.distance = checked ((int)Math.Round(Design.Drawing.MeasurePointDistance(point, point1))); this.distance = checked ((int)Math.Round((double)this.distance / (double)this._PointCollection.Count)); int count = checked (this._PointCollection.Count - 1); for (int i = 0; i <= count; i = checked (i + 1)) { List <Rectangle> rectangles = this._PointPosition; rectangle = new Rectangle(checked (checked (circleWidth + 6) - checked ((int)Math.Round((double)this._PointCollection[i].CircleWidth / 2))), checked (checked (checked (this.Height - (checked (circleWidth + 6))) - checked ((int)Math.Round((double)this._PointCollection[i].CircleWidth / 2))) - checked (this.distance * (checked (i + 1)))), this._PointCollection[i].CircleWidth, this._PointCollection[i].CircleWidth); rectangles.Add(rectangle); } } Pen pen = new Pen(this._LineColor); SolidBrush solidBrush = new SolidBrush(this._LineColor); Pen pen1 = new Pen(this._HoverColor); graphics.DrawLine(pen, point, point1); Point point2 = new Point(checked (checked (circleWidth + 6) - checked ((int)Math.Round((double)this._StartPointWidth / 2))), checked (checked (this.Height - (checked (circleWidth + 6))) - checked ((int)Math.Round((double)this._StartPointWidth / 2)))); System.Drawing.Size size = new System.Drawing.Size(this._StartPointWidth, this._StartPointWidth); rectangle = new Rectangle(point2, size); switch (taskShape) { case TaskShape.Circle: graphics.FillEllipse(solidBrush, rectangle); break; case TaskShape.Rectangle: graphics.FillRectangle(solidBrush, rectangle); break; case TaskShape.Pie: graphics.FillPie(solidBrush, rectangle, PieAngle.StartAngle, PieAngle.SweepAngle); break; } if (this._PointPosition.Count > 0) { int num = checked (this._PointCollection.Count - 1); for (int j = 0; j <= num; j = checked (j + 1)) { SolidBrush solidBrush1 = new SolidBrush((this._PointCollection[j].Finished ? this._FinishedColor : this._PointCollection[j].CirceColor)); switch (taskShape) { case TaskShape.Circle: graphics.FillEllipse(solidBrush1, this._PointPosition[j]); break; case TaskShape.Rectangle: graphics.FillRectangle(solidBrush1, this._PointPosition[j]); break; case TaskShape.Pie: graphics.FillPie(solidBrush1, this._PointPosition[j], PieAngle.StartAngle, PieAngle.SweepAngle); break; } if (this._HotPoint != rectangle1 && j == this._HotIndex && this._PointCollection[this._HotIndex].Enabled) { solidBrush1.Color = this._HoverColor; } SizeF sizeF = graphics.MeasureString(this._PointCollection[j].Text, this.Font); int num1 = checked (checked (circleWidth * 2) + 6); rectangle = this._PointPosition[j]; Rectangle rectangle2 = new Rectangle(num1, checked (checked (rectangle.Y + checked ((int)Math.Round((double)this._PointCollection[j].CircleWidth / 2))) - checked ((int)Math.Round((double)((float)(sizeF.Height / 2f))))), checked ((int)Math.Round((double)((float)(sizeF.Width + 2f)))), checked (this.distance - checked ((int)Math.Round((double)((float)(sizeF.Height + 2f)))))); this._TextRectangles.Add(rectangle2); graphics.DrawString(this._PointCollection[j].Text, this.Font, solidBrush1, rectangle2); int num2 = checked ((int)Math.Round((double)this._PointCollection[j].CircleWidth / 4)); if (this._PointCollection[j].Icon != null) { Image icon = this._PointCollection[j].Icon; rectangle = this._PointPosition[j]; int x = checked (rectangle.X + num2); Rectangle item = this._PointPosition[j]; Rectangle rectangle3 = new Rectangle(x, checked (item.Y + num2), checked (num2 * 2), checked (num2 * 2)); graphics.DrawImage(icon, rectangle3); } } if (this._HotPoint != rectangle1) { if (this._PointCollection[this._HotIndex].Enabled) { switch (taskShape) { case TaskShape.Circle: graphics.DrawEllipse(pen1, this._HotPoint); break; case TaskShape.Rectangle: graphics.DrawRectangle(pen1, this._HotPoint); break; case TaskShape.Pie: graphics.DrawPie(pen1, this._HotPoint, PieAngle.StartAngle, PieAngle.SweepAngle); break; } } } } base.OnPaint(e); }
public List <IData3DSet> AddGridCoords() { string fontname = "MS Sans Serif"; { Font fnt = new Font(fontname, 20F); int bitmapwidth, bitmapheight; Bitmap text_bmp = new Bitmap(300, 30); using (Graphics g = Graphics.FromImage(text_bmp)) { SizeF sz = g.MeasureString("-99999,-99999", fnt); bitmapwidth = (int)sz.Width + 4; bitmapheight = (int)sz.Height + 4; } var datasetMapImgLOD1 = Data3DSetClass <TexturedQuadData> .Create("text bitmap LOD1", Color.White, 1.0f); var datasetMapImgLOD2 = Data3DSetClass <TexturedQuadData> .Create("text bitmap LOD2", Color.FromArgb(128, Color.White), 1.0f); int textheightly = 50; int textwidthly = textheightly * bitmapwidth / bitmapheight; int gridwideLOD1 = (int)Math.Floor((MaxGridPos.X - MinGridPos.X) / gridunitSize + 1); int gridhighLOD1 = (int)Math.Floor((MaxGridPos.Y - MinGridPos.Y) / gridunitSize + 1); int gridwideLOD2 = (int)Math.Floor((MaxGridPos.X - MinGridPos.X) / (gridunitSize * 10) + 1); int gridhighLOD2 = (int)Math.Floor((MaxGridPos.Y - MinGridPos.Y) / (gridunitSize * 10) + 1); int texwide = 1024 / bitmapwidth; int texhigh = 1024 / bitmapheight; int numtexLOD1 = (int)Math.Ceiling((gridwideLOD1 * gridhighLOD1) * 1.0 / (texwide * texhigh)); int numtexLOD2 = (int)Math.Ceiling((gridwideLOD2 * gridhighLOD2) * 1.0 / (texwide * texhigh)); List <TexturedQuadData> basetexturesLOD1 = Enumerable.Range(0, numtexLOD1).Select(i => new TexturedQuadData(null, null, new Bitmap(1024, 1024))).ToList(); List <TexturedQuadData> basetexturesLOD2 = Enumerable.Range(0, numtexLOD2).Select(i => new TexturedQuadData(null, null, new Bitmap(1024, 1024))).ToList(); for (float x = MinGridPos.X; x < MaxGridPos.X; x += gridunitSize) { for (float z = MinGridPos.Y; z <= MaxGridPos.Y; z += gridunitSize) { int num = (int)(Math.Floor((x - MinGridPos.X) / gridunitSize) * gridwideLOD1 + Math.Floor((z - MinGridPos.Y) / gridunitSize)); int tex_x = (num % texwide) * bitmapwidth; int tex_y = ((num / texwide) % texhigh) * bitmapheight; int tex_n = num / (texwide * texhigh); //Console.WriteLine("num {0} tex_x {1} tex_y {2} txt_n {3}", num, tex_x, tex_y, tex_n); DrawGridBitmap(basetexturesLOD1[tex_n].Texture, x, z, fnt, tex_x, tex_y); datasetMapImgLOD1.Add(basetexturesLOD1[tex_n].Horz( x, z, x + textwidthly, z + textheightly, tex_x, tex_y, tex_x + bitmapwidth, tex_y + bitmapheight )); } } for (float x = MinGridPos.X; x < MaxGridPos.X; x += gridunitSize * 10) { for (float z = MinGridPos.Y; z <= MaxGridPos.Y; z += gridunitSize * 10) { int num = (int)(Math.Floor((x - MinGridPos.X) / (gridunitSize * 10)) * gridwideLOD2 + Math.Floor((z - MinGridPos.Y) / (gridunitSize * 10))); int tex_x = (num % texwide) * bitmapwidth; int tex_y = ((num / texwide) % texhigh) * bitmapheight; int tex_n = num / (texwide * texhigh); DrawGridBitmap(basetexturesLOD2[tex_n].Texture, x, z, fnt, tex_x, tex_y); datasetMapImgLOD2.Add(basetexturesLOD2[tex_n].Horz( x, z, x + textwidthly * 10, z + textheightly * 10, tex_x, tex_y, tex_x + bitmapwidth, tex_y + bitmapheight )); } } _datasets.Add(datasetMapImgLOD1); _datasets.Add(datasetMapImgLOD2); } return(_datasets); }
private void _PrintDocument_PrintPage(object sender, PrintPageEventArgs e) { Graphics gs = e.Graphics; #region 绘制磅单 int paddingtop = paddingtopAll + 80; //矩形距离上部的距离 float cloum1 = 170; //供应商的宽 float cloum2 = 50; //车数的宽 float cloum3 = 71; //重量的宽 int RowWeight = Convert.ToInt32(cloum1 + cloum2 + cloum3 * 8); //列表宽 int Height = LineHeight * (_Transport.Count + 1); //矩形的高 int top = 0; Rectangle r = new Rectangle(paddingleft, paddingtop, RowWeight, Height); //矩形的位置和大小 Pen pen = new Pen(Color.Black, 1); //画笔 gs.DrawRectangle(pen, r); string title = "企业过磅日报表(出场煤)"; Font titlefont = new Font("宋体", 20, FontStyle.Bold, GraphicsUnit.Pixel); gs.DrawString(title, titlefont, Brushes.Black, (RowWeight - gs.MeasureString(title, titlefont).Width) / 2, paddingtopAll); gs.DrawString("统计时间:" + StartTime.ToString("yyyy-MM-dd") + "-" + EndTime.ToString("yyyy-MM-dd") + " 指标日期:" + DateTime.Now.ToString("yyyy-MM-dd") + " 单位:吨", ContentFont, Brushes.Black, paddingleft + 10, paddingtopAll + 55); int seralinumber = 1;//序号 //列标题 //供应商 string SupplierNameTitle = "收货单位"; SizeF SupplierNameSizeTitle = gs.MeasureString(SupplierNameTitle, ContentFont); gs.DrawString(SupplierNameTitle, ContentFont, Brushes.Black, paddingleft + (cloum1 - SupplierNameSizeTitle.Width) / 2, paddingtop + (LineHeight - SupplierNameSizeTitle.Height) / 2); //煤种 string FuelKindNameTitle = "煤种"; SizeF FuelKindNameSizeTitle = gs.MeasureString(FuelKindNameTitle, ContentFont); gs.DrawString(FuelKindNameTitle, ContentFont, Brushes.Black, paddingleft + cloum1 + (cloum2 - FuelKindNameSizeTitle.Width) / 2, paddingtop + (LineHeight - FuelKindNameSizeTitle.Height) / 2); //车数 string MineNameTitle = "车数"; SizeF MineNameSizeTitle = gs.MeasureString(MineNameTitle, ContentFont); gs.DrawString(MineNameTitle, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + (cloum3 - MineNameSizeTitle.Width) / 2, paddingtop + (LineHeight - MineNameSizeTitle.Height) / 2); //毛重 string GrossWeightTitle = "毛重(T)"; SizeF GrossWeightSizeTitle = gs.MeasureString(GrossWeightTitle, ContentFont); gs.DrawString(GrossWeightTitle, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 + (cloum3 - GrossWeightSizeTitle.Width) / 2, paddingtop + (LineHeight - GrossWeightSizeTitle.Height) / 2); //皮重 string TareWeightTitle = "皮重(T)"; SizeF TareWeightSizeTitle = gs.MeasureString(TareWeightTitle, ContentFont); gs.DrawString(TareWeightTitle, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 * 2 + (cloum3 - TareWeightSizeTitle.Width) / 2, paddingtop + (LineHeight - TareWeightSizeTitle.Height) / 2); //净重 string SuttleWeightTitle = "净重(T)"; SizeF SuttleWeightSizeTitle = gs.MeasureString(SuttleWeightTitle, ContentFont); gs.DrawString(SuttleWeightTitle, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 * 3 + (cloum3 - SuttleWeightSizeTitle.Width) / 2, paddingtop + (LineHeight - SuttleWeightSizeTitle.Height) / 2); gs.DrawLine(pen, paddingleft, paddingtop + LineHeight, paddingleft + RowWeight, paddingtop + LineHeight); foreach (CmcsSaleFuelTransport item in _Transport) { top = LineHeight * seralinumber; //收货单位 string SupplierName = item.SupplierId; SizeF SupplierNameSize = gs.MeasureString(SupplierName, ContentFont); if (SupplierName == "合计") { gs.DrawString(SupplierName, ContentFont, Brushes.Black, paddingleft + (cloum1 - SupplierNameSize.Width) / 2, paddingtop + top + (LineHeight - SupplierNameSize.Height) / 2); } else { gs.DrawString(SupplierName, ContentFont, Brushes.Black, paddingleft + (cloum1 - SupplierNameSize.Width) / 2, paddingtop + top + (LineHeight - SupplierNameSize.Height) / 2); } //煤种 string FuelKindName = item.FuelKindId; SizeF FuelKindNameSize = gs.MeasureString(FuelKindName, ContentFont); if (SupplierName == "") { gs.DrawString(FuelKindName, ContentFont, Brushes.Black, paddingleft + cloum1 + (cloum2 - FuelKindNameSize.Width) / 2, paddingtop + top + (LineHeight - FuelKindNameSize.Height) / 2); } else { gs.DrawString(FuelKindName, ContentFont, Brushes.Black, paddingleft + cloum1 + (cloum2 - FuelKindNameSize.Width) / 2, paddingtop + top + (LineHeight - FuelKindNameSize.Height) / 2); } //车数 string MineName = item.IsFinish.ToString(); SizeF MineNameSize = gs.MeasureString(MineName, ContentFont); gs.DrawString(MineName, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + (cloum3 - MineNameSize.Width) / 2, paddingtop + top + (LineHeight - MineNameSize.Height) / 2); //毛重 string GrossWeight = item.GrossWeight.ToString("F2"); SizeF GrossWeightSize = gs.MeasureString(GrossWeight, ContentFont); gs.DrawString(GrossWeight, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 + (cloum3 - GrossWeightSize.Width) / 2, paddingtop + top + (LineHeight - GrossWeightSize.Height) / 2); //皮重 string TareWeight = item.TareWeight.ToString("F2"); SizeF TareWeightSize = gs.MeasureString(TareWeight, ContentFont); gs.DrawString(TareWeight, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 * 2 + (cloum3 - TareWeightSize.Width) / 2, paddingtop + top + (LineHeight - TareWeightSize.Height) / 2); //净重 string SuttleWeight = item.SuttleWeight.ToString("F2"); SizeF SuttleWeightSize = gs.MeasureString(SuttleWeight, ContentFont); gs.DrawString(SuttleWeight, ContentFont, Brushes.Black, paddingleft + cloum1 + cloum2 + cloum3 * 3 + (cloum3 - SuttleWeightSize.Width) / 2, paddingtop + top + (LineHeight - SuttleWeightSize.Height) / 2); gs.DrawLine(pen, paddingleft, paddingtop + LineHeight * seralinumber, paddingleft + RowWeight, paddingtop + LineHeight * seralinumber); seralinumber++; } gs.DrawLine(pen, paddingleft + cloum1, paddingtop, paddingleft + cloum1, paddingtop + Height); gs.DrawLine(pen, paddingleft + cloum1 + cloum2, paddingtop, paddingleft + cloum1 + cloum2, paddingtop + Height); gs.DrawLine(pen, paddingleft + cloum1 + cloum2 + cloum3, paddingtop, paddingleft + cloum1 + cloum2 + cloum3, paddingtop + Height); gs.DrawLine(pen, paddingleft + cloum1 + cloum2 + cloum3 * 2, paddingtop, paddingleft + cloum1 + cloum2 + cloum3 * 2, paddingtop + Height); gs.DrawLine(pen, paddingleft + cloum1 + cloum2 + cloum3 * 3, paddingtop, paddingleft + cloum1 + cloum2 + cloum3 * 3, paddingtop + Height); #endregion }
public static Size Round(SizeF s) { return(new Size((int)System.Math.Round(s.Width), (int)System.Math.Round(s.Height))); }
public void CreatePDF(Stream stream) { var doc = new GcPdfDocument(); var page = doc.NewPage(); var g = page.Graphics; // By default, GcPdf uses 72dpi: const float In = 72; // TextFormat class is used throughout all GcPdf text rendering to specify // font and other character formatting: var tf = new TextFormat() { Font = StandardFonts.Times, FontSize = 12 }; // 1. // The easiest way to render a short string on a page at an arbitrary location, // when you are 100% sure that the string will fit in the available space, // is to use the GcGraphics.DrawString() overload accepting jus the point // at which to draw the string: g.DrawString( "1. Test string. Please read the extensive comments in this sample's code.\r\n" + "(Note that line breaks are allowed even in the simplest DrawString overload.)", tf, new PointF(In, In)); // 2. // Another overload taking a rectangle instead, plus alignment and wrapping // options, is also available and provides a bit more flexibility. // The parameters are: // - the text string; // - the text format; // - the layout rectangle; // - (optional) text alignment (the default is leading, left for LTR languages); // - (optional) paragraph alignment (the default is near, top for top-to-bottom flow); // - (optional) word wrapping (the default is true): g.DrawString( "2. A longer test string which will probably need more than the allocated " + "4 inches so quite possibly will wrap to show that DrawString can do that.", tf, new RectangleF(In, In * 2, In * 4, In), TextAlignment.Leading, ParagraphAlignment.Near, true); // 3. // Complementary to DrawString, a MeasureString() method is available // (with several different overloads), and can be used in pair with // DrawString when more control over text layout is needed: const string tstr3 = "3. Test string to demo MeasureString() used with DrawString()."; // Available layout size: SizeF layoutSize = new SizeF(In * 3, In * 0.8f); SizeF s = g.MeasureString(tstr3, tf, layoutSize, out int fitCharCount); // Show the passed in size in red, the measured size in blue, // and draw the string within the returned size as bounds: PointF pt = new PointF(In, In * 3); g.DrawRectangle(new RectangleF(pt, layoutSize), Color.Red); g.DrawRectangle(new RectangleF(pt, s), Color.Blue); g.DrawString(tstr3, tf, new RectangleF(pt, s)); // 4. // A much more powerful and with better performance, way to render text // is to use TextLayout. (TextLayout is used anyway by DrawString/MeasureString, // so when you use TextLayout directly, you basically cut the work in half.) // A TextLayout instance represents one or more paragraphs of text, with // the same paragraph formatting (character formats may be different, // see MultiFormattedText). var tl = g.CreateTextLayout(); // To add text, use Append() or AppendLine() methods: tl.Append("4. First test string added to TextLayout. ", tf); tl.Append("Second test string added to TextLayout, continuing the same paragraph. ", tf); // Add a line break, effectively starting a new paragraph: tl.AppendLine(); tl.Append("Third test string added to TextLayout, a new paragraph. ", tf); tl.Append("Fourth test string, with a different char formatting. ", new TextFormat(tf) { Font = StandardFonts.TimesBoldItalic, ForeColor = Color.DarkSeaGreen, }); // Text can be added to TextLayout without explicit TextFormat: tl.Append("Fifth test string, using the TextLayout's default format."); // ...but in that case at least the Font must be specified on the // TextLayout's DefaultFormat, otherwise PerformLayout (below) will fail: tl.DefaultFormat.Font = StandardFonts.TimesItalic; // Specify the layout, such as max available size etc. // Here we only provide the max width, but many more parameters can be set: tl.MaxWidth = page.Size.Width - In * 2; // Paragraph formatting can also be set, here we set first line offset, // spacing between paragraphs and line spacing: tl.FirstLineIndent = In * 0.5f; tl.ParagraphSpacing = In * 0.05f; tl.LineSpacingScaleFactor = 0.8f; // When all text has been added, and layout options specified, // the TextLayout needs to calculate the glyphs needed to render // the text, and perform the layout. This can be done with a // single call: tl.PerformLayout(true); // Now we can draw it on the page: pt = new PointF(In, In * 4); g.DrawTextLayout(tl, pt); // TextLayout provides info about the text including the measured bounds // and much more. Here we draw the bounding box in orange red: g.DrawRectangle(new RectangleF(pt, tl.ContentRectangle.Size), Color.OrangeRed); // 5. // TextLayout can be re-used to draw different paragraph(s), this can be useful // when you need to render a different text with the same paragraph formatting. // The Clear() call removes the text but preserves paragraph formatting: tl.Clear(); tl.Append("5. This is text rendered re-using the same TextLayout. "); tl.Append("More text added to TextLayout being re-used, continuing the same paragraph. ", tf); tl.Append("And finally, some more text added.", tf); // The necessary call to calculate the glyphs and perform layout: tl.PerformLayout(true); // Render the text: g.DrawTextLayout(tl, new PointF(In, In * 5)); // Done: doc.Save(stream); }
private void DrawValue(Graphics g, int iValue, int iPosition, int iSpaceAvailable) { // The sizing operation is common to all options StringFormat format = new StringFormat(StringFormatFlags.MeasureTrailingSpaces); if (_VerticalNumbers) { format.FormatFlags |= StringFormatFlags.DirectionVertical; } SizeF size = g.MeasureString((iValue).ToString(), this.Font, iSpaceAvailable, format); Point drawingPoint; int iX = 0; int iY = 0; if (this.Orientation == Orientations.orHorizontal) { switch (_RulerAlignment) { case RulerAlignments.raBottomOrRight: { iX = iPosition + iSpaceAvailable - (int)size.Width - 2; iY = 2; break; } case RulerAlignments.raMiddle: { iX = iPosition + iSpaceAvailable - (int)size.Width / 2; iY = (Height - (int)size.Height) / 2 - 2; break; } case RulerAlignments.raTopOrLeft: { iX = iPosition + iSpaceAvailable - (int)size.Width - 2; iY = Height - 2 - (int)size.Height; break; } } drawingPoint = new Point(iX - (int)size.Width, iY); g.DrawString(iValue.ToString(), this.Font, new SolidBrush(this.ForeColor), drawingPoint); } else { switch (_RulerAlignment) { case RulerAlignments.raBottomOrRight: { iX = 2; iY = iPosition + iSpaceAvailable - (int)size.Height - 2; break; } case RulerAlignments.raMiddle: { iX = (Width - (int)size.Width) / 2 - 1; iY = iPosition + iSpaceAvailable - (int)size.Height / 2; break; } case RulerAlignments.raTopOrLeft: { iX = Width - 2 - (int)size.Width; iY = iPosition + iSpaceAvailable - (int)size.Height - 2; break; } } drawingPoint = new Point(iX, iY); g.DrawString(iValue.ToString(), this.Font, new SolidBrush(this.ForeColor), drawingPoint, format); } }
// The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width private void Calculate(Graphics g) { if(PageNumber == 0) // Just calculate once { SizeF tmpSize = new SizeF(); Font tmpFont; float tmpWidth; TheDataGridViewWidth = 0; for(int i = 0;i < TheDataGridView.Columns.Count;i++) { tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font; if(tmpFont == null){ // If there is no special HeaderFont style, then use the default DataGridView font style tmpFont = TheDataGridView.DefaultCellStyle.Font; } tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText,tmpFont); tmpWidth = tmpSize.Width; RowHeaderHeight = tmpSize.Height; for(int j = 0;j < TheDataGridView.Rows.Count;j++) { tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font; if(tmpFont == null){ // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control tmpFont = TheDataGridView.DefaultCellStyle.Font; } tmpSize = g.MeasureString("Anything",tmpFont); RowsHeight.Add(tmpSize.Height); tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(),tmpFont); if(tmpSize.Width > tmpWidth){ tmpWidth = tmpSize.Width; } } if(TheDataGridView.Columns[i].Visible){ TheDataGridViewWidth += tmpWidth; } ColumnsWidth.Add(tmpWidth); } // Define the start/stop column points based on the page width and the DataGridView Width // We will use this to determine the columns which are drawn on each page and how wrapping will be handled // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine int k; int mStartPoint = 0; for(k = 0;k < TheDataGridView.Columns.Count;k++){ if(TheDataGridView.Columns[k].Visible) { mStartPoint = k; break; } } int mEndPoint = TheDataGridView.Columns.Count; for(k = TheDataGridView.Columns.Count - 1;k >= 0;k--){ if(TheDataGridView.Columns[k].Visible) { mEndPoint = k + 1; break; } } float mTempWidth = TheDataGridViewWidth; float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin; // We only care about handling where the total datagridview width is bigger then the print area if(TheDataGridViewWidth > mTempPrintArea) { mTempWidth = 0.0F; for(k = 0;k < TheDataGridView.Columns.Count;k++) { if(TheDataGridView.Columns[k].Visible) { mTempWidth += ColumnsWidth[k]; // If the width is bigger than the page area, then define a new column print range if(mTempWidth > mTempPrintArea) { mTempWidth -= ColumnsWidth[k]; mColumnPoints.Add(new int[] { mStartPoint,mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mStartPoint = k; mTempWidth = ColumnsWidth[k]; } } // Our end point is actually one index above the current index mEndPoint = k + 1; } } // Add the last set of columns mColumnPoints.Add(new int[] { mStartPoint,mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mColumnPoint = 0; } }
// The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width private void Calculate(Graphics g) { if (PageNumber == 0) // Just calculate once { SizeF tmpSize = new SizeF(); Font tmpFont; float tmpWidth; TheDataGridViewWidth = 0; for (int i = 0; i < TheDataGridView.Columns.Count; i++) { tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font; if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style { tmpFont = TheDataGridView.DefaultCellStyle.Font; } tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont); tmpWidth = tmpSize.Width; RowHeaderHeight = tmpSize.Height; for (int j = 0; j < TheDataGridView.Rows.Count; j++) { tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font; if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control { tmpFont = TheDataGridView.DefaultCellStyle.Font; } tmpSize = g.MeasureString("Anything", tmpFont); RowsHeight.Add(tmpSize.Height); tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont); if (tmpSize.Width > tmpWidth) { tmpWidth = tmpSize.Width; } } if (TheDataGridView.Columns[i].Visible) { TheDataGridViewWidth += tmpWidth; } ColumnsWidth.Add(tmpWidth); } // Define the start/stop column points based on the page width and the DataGridView Width // We will use this to determine the columns which are drawn on each page and how wrapping will be handled // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine int k; int mStartPoint = 0; for (k = 0; k < TheDataGridView.Columns.Count; k++) { if (TheDataGridView.Columns[k].Visible) { mStartPoint = k; break; } } int mEndPoint = TheDataGridView.Columns.Count; for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--) { if (TheDataGridView.Columns[k].Visible) { mEndPoint = k + 1; break; } } float mTempWidth = TheDataGridViewWidth; float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin; // We only care about handling where the total datagridview width is bigger then the print area if (TheDataGridViewWidth > mTempPrintArea) { mTempWidth = 0.0F; for (k = 0; k < TheDataGridView.Columns.Count; k++) { if (TheDataGridView.Columns[k].Visible) { mTempWidth += ColumnsWidth[k]; // If the width is bigger than the page area, then define a new column print range if (mTempWidth > mTempPrintArea) { mTempWidth -= ColumnsWidth[k]; mColumnPoints.Add(new int[] { mStartPoint, mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mStartPoint = k; mTempWidth = ColumnsWidth[k]; } } // Our end point is actually one index above the current index mEndPoint = k + 1; } } // Add the last set of columns mColumnPoints.Add(new int[] { mStartPoint, mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mColumnPoint = 0; } }
public static void SizeSetTest(float x, float y) { var size = new SizeF(x, y); var rect = new RectangleF(10, 10, 10, 10); rect.Size = size; Assert.Equal(size, rect.Size); Assert.Equal(size.Width, rect.Width); Assert.Equal(size.Height, rect.Height); }
public DistanceTestCase Shift(SizeF shift) { return(new DistanceTestCase(a + shift, b + shift, x + shift, distance)); }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { G = e.Graphics; G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; G.Clear(BackColor); G.SmoothingMode = SmoothingMode.AntiAlias; GP1 = ThemeModule.CreateRound(0, 0, Width - 1, Height - 1, 7); GP2 = ThemeModule.CreateRound(1, 1, Width - 3, Height - 3, 7); if (IsMouseDown) { PB1 = new PathGradientBrush(GP1); PB1.CenterColor = Color.FromArgb(60, 60, 60); PB1.SurroundColors = new Color[] { Color.FromArgb(55, 55, 55) }; PB1.FocusScales = new PointF(0.8f, 0.5f); G.FillPath(PB1, GP1); } else { GB1 = new LinearGradientBrush(ClientRectangle, Color.FromArgb(60, 60, 60), Color.FromArgb(55, 55, 55), 90f); G.FillPath(GB1, GP1); } G.DrawPath(P1, GP1); G.DrawPath(P2, GP2); SZ1 = G.MeasureString(Text, Font); PT1 = new PointF(5, Height / 2 - SZ1.Height / 2); if (IsMouseDown) { PT1.X += 1f; PT1.Y += 1f; } G.DrawString(Text, Font, Brushes.Black, PT1.X + 1, PT1.Y + 1); G.DrawString(Text, Font, Brushes.White, PT1); }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { G = e.Graphics; G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; G.Clear(BackColor); G.SmoothingMode = SmoothingMode.AntiAlias; GP1 = new GraphicsPath(); GP1.AddEllipse(0, 2, Height - 5, Height - 5); PB1 = new PathGradientBrush(GP1); PB1.CenterColor = Color.FromArgb(50, 50, 50); PB1.SurroundColors = new Color[] { Color.FromArgb(45, 45, 45) }; PB1.FocusScales = new PointF(0.3f, 0.3f); G.FillPath(PB1, GP1); G.DrawEllipse(P1, 0, 2, Height - 5, Height - 5); G.DrawEllipse(P2, 1, 3, Height - 7, Height - 7); if (_Checked) { G.FillEllipse(Brushes.Black, 6, 8, Height - 15, Height - 15); G.FillEllipse(Brushes.White, 5, 7, Height - 15, Height - 15); } SZ1 = G.MeasureString(Text, Font); PT1 = new PointF(Height - 3, Height / 2 - SZ1.Height / 2); G.DrawString(Text, Font, Brushes.Black, PT1.X + 1, PT1.Y + 1); G.DrawString(Text, Font, Brushes.White, PT1); }