Related
I've been drawn multiple rectangles on the picturebox image.I want to resize all that rectangles using mouse events. Can anyone help me out regarding this?
public List<rectangle> listRec = new List<rectangle>();
Graphics g;
//private Graphics g;
Point startPos;
Point currentPos;
bool drawing;
Rectangle r1;
Rectangle rect = new Rectangle();
private Rectangle getRectangle()
{
r1 = new Rectangle(
Math.Min(startPos.X, currentPos.X),
Math.Min(startPos.Y, currentPos.Y),
Math.Abs(startPos.X - currentPos.X),
Math.Abs(startPos.Y - currentPos.Y));
return r1;
}
private void button1_Click(object sender, EventArgs e)
{
String data;
Font font = new Font("Arial", 14);
arg1 = Convert.ToInt32(textBox1.Text);
arg2 = Convert.ToInt32(textBox2.Text);
Rectangle rect = new Rectangle();
rect.Size = new Size(40, 65);
for (int x = 0; x < arg1; x++)
{
// rect.X = x * rect.Width;
rect.X = x * (rect.Width + 30) + 73;
for (int y = 0; y < arg2; y++)
{
rect.Y = y * (rect.Height + 35) + 38;
listRec.Add(rect);
data = rect.ToString();
TextWriter txt = new StreamWriter("E:\\B1Pockets.txt", true);
txt.WriteLine(data);
txt.Close();
// MessageBox.Show(rect.ToString());
}
}
foreach (Rectangle rec in listRec)
{
g = pictureBox1.CreateGraphics();
Pen p = new Pen(Color.Red, 3);
g.DrawRectangle(p, rec);
g.DrawString("p1", font, new SolidBrush(Color.Yellow), (rect.Width + 30), 35);
g.DrawString("p2", font, new SolidBrush(Color.Yellow), (rect.Width + 40) + 60, 35);
g.DrawString("p3", font, new SolidBrush(Color.Yellow), (rect.Width + 40) + 130, 35);
g.DrawString("p4", font, new SolidBrush(Color.Yellow), (rect.Width + 30), (rect.Height + 30) + 40);
g.DrawString("p5", font, new SolidBrush(Color.Yellow), (rect.Width + 40) + 60, (rect.Height + 30) + 40);
g.DrawString("p6", font, new SolidBrush(Color.Yellow), (rect.Width + 40) + 130, (rect.Height + 30) + 40);
}
}
I've tried this code to my application.I drawn rectangles in 2*3 manner.and also draw a big rectangle above it.In short my picturebox containing many rectangles and i want to add resizing options for all the rectangles in c#
I'm trying to create UX that is familiar to Bootstrap 4 Radio Button Group.
I know I can change Appearance=Button but this wont give me desired effect.
This is what I get:
and this is what I want:
I found similar question, but it uses WPF and I need WinForms.
Second one suggest using list view, but in that question list is vertical, but I need horizontal align.
I'm looking for a control that has first button rounded on left and last on right (just like on second image)
My question is: Does anyone know is such control exists? If yes I'll be grateful for anu links, if no then any tips regarding how to create such control are welcome (I know how to create custom controls and paint them so links on how to get started with user controls aren't needed)
EDIT
Because my question got down voted I'm adding code that I've written to create such control.
This is result I got:
and here is code:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace UserControls
{
public sealed class RadioGroupBox: UserControl
{
public RadioGroupBox()
{
DoubleBuffered = true;
ResizeRedraw = true;
Padding = new Padding(2);
CalculateItemWidth();
}
public event EventHandler SelectedIndexChanged;
protected override Size DefaultSize => new Size(200, 30);
private int _cornerRadius = 2;
public int CornerRadius
{
get => _cornerRadius;
set
{
if(value==_cornerRadius) return;
_cornerRadius = value;
Invalidate();
}
}
private string[] _items = {"A", "B", "C"};
[Category("Data")]
//[DefaultValue(null)]
[Description("Items")]
public string[] Items
{
get => _items;
set
{
if(value==_items) return;
_items = value;
CalculateItemWidth();
Invalidate();
}
}
private int _itemWidth;
private void CalculateItemWidth()
{
if (_items == null || _items.Length == 0)
{
_itemWidth = 0;
return;
}
var width = ClientRectangle.Width - Padding.Horizontal;
_itemWidth = width / _items.Length;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
CalculateItemWidth();
//Debug.WriteLine(_itemWidth);
CalculateSelectedItem(e.Location);
}
private int _selectedIndex = -1;
public int SelectedIndex
{
get => _selectedIndex;
set
{
if(value==_selectedIndex) return;
_selectedIndex = value;
Invalidate();
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
_click = true;
if (_hoverPos > -1)
{
if (_selectedIndex != _hoverPos)
{
_selectedIndex = _hoverPos;
SelectedIndexChanged?.Invoke(this, e);
}
}
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
_click = false;
Invalidate();
}
private int _hoverPos = -1;
private bool _click;
private void CalculateSelectedItem(Point mouseLocation)
{
var clientRect = GetPaddedRectangle();
int pos;
if (!clientRect.Contains(mouseLocation))
{
pos = -1;
}
else
{
pos = mouseLocation.X / _itemWidth;
if (pos > _items.Length - 1)
{
pos = -1;
}
}
if (pos != _hoverPos)
{
_hoverPos = pos;
Invalidate();
}
//Debug.WriteLine(_hoverPos);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
CalculateItemWidth();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
var rect = GetPaddedRectangle();
LinearGradientBrush normalBrush = new LinearGradientBrush(rect,
Color.White,
Color.LightBlue,
LinearGradientMode.Vertical);
LinearGradientBrush hoverBlush = new LinearGradientBrush(rect,
Color.RoyalBlue,
Color.MediumBlue,
LinearGradientMode.Vertical);
LinearGradientBrush selectedBrush = new LinearGradientBrush(rect,
Color.DodgerBlue,
Color.Blue,
LinearGradientMode.Vertical);
//e.Graphics.FillRectangle(Brushes.Aqua, this.ClientRectangle);
using (GraphicsPath path = RoundedRect(rect, _cornerRadius))
{
e.Graphics.FillPath(normalBrush, path);
e.Graphics.DrawPath(Pens.DodgerBlue, path);
}
if (_items == null || _items.Length == 0) return;
if (_hoverPos > -1 || _selectedIndex>-1)
{
var flags = RectangleCorners.None;
if (_hoverPos == 0) flags = RectangleCorners.TopLeft | RectangleCorners.BottomLeft;
if(_hoverPos==_items.Length-1) flags = RectangleCorners.TopRight | RectangleCorners.BottomRight;
var rect2 = new Rectangle(rect.X + _hoverPos * _itemWidth, rect.Y, _itemWidth, rect.Height);
if (_hoverPos == _items.Length - 1)
{
rect2 = new Rectangle(rect.X + _hoverPos * _itemWidth, rect.Y, rect.Width-_hoverPos*_itemWidth, rect.Height);
}
if (_hoverPos > -1 && _selectedIndex != _hoverPos)
{
using (GraphicsPath path = RoundedRect(rect2, _cornerRadius, flags))
{
e.Graphics.FillPath(_click ? Brushes.SteelBlue : hoverBlush, path);
}
}
if (_selectedIndex > -1)
{
rect2 = new Rectangle(rect.X + _selectedIndex * _itemWidth, rect.Y, _itemWidth, rect.Height);
if (_selectedIndex == _items.Length - 1)
{
rect2 = new Rectangle(rect.X + _selectedIndex * _itemWidth, rect.Y, rect.Width - _selectedIndex * _itemWidth, rect.Height);
}
flags = RectangleCorners.None;
if (_selectedIndex == 0) flags = RectangleCorners.TopLeft | RectangleCorners.BottomLeft;
if (_selectedIndex == _items.Length - 1) flags = RectangleCorners.TopRight | RectangleCorners.BottomRight;
using (GraphicsPath path = RoundedRect(rect2, _cornerRadius, flags))
{
e.Graphics.FillPath(selectedBrush, path);
}
}
}
//pionowe linie
for (int i = 1; i <= _items.Length-1; i++)
{
e.Graphics.DrawLine(Pens.DodgerBlue,rect.X+i*_itemWidth,rect.Y, rect.X + i * _itemWidth, rect.Y+rect.Height);
}
StringFormat sf = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
};
for (var i = 0; i < _items.Length; i++)
{
string item = _items[i];
e.Graphics.DrawString(item, Font, i==_hoverPos?Brushes.White:Brushes.DodgerBlue, new Rectangle(rect.X+i* _itemWidth, rect.Y, _itemWidth, rect.Height), sf);
}
//Debug.WriteLine(MousePosition);
}
private Rectangle GetPaddedRectangle()
{
var rect = ClientRectangle;
var pad = Padding;
return new Rectangle(rect.X + pad.Left,
rect.Y + pad.Top,
rect.Width - pad.Horizontal,
rect.Height - pad.Vertical);
}
[Flags]
public enum RectangleCorners
{
None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8,
All = TopLeft | TopRight | BottomLeft | BottomRight
}
public static GraphicsPath RoundedRect(Rectangle bounds, int radius, RectangleCorners corners = RectangleCorners.All)
{
int diameter = radius * 2;
GraphicsPath path = new GraphicsPath();
if (radius == 0)
{
path.AddRectangle(bounds);
return path;
}
// Make a GraphicsPath to draw the rectangle.
PointF point1, point2;
// Upper left corner.
if ((RectangleCorners.TopLeft & corners) == RectangleCorners.TopLeft)
{
RectangleF corner = new RectangleF(bounds.X, bounds.Y,diameter, diameter);
path.AddArc(corner, 180, 90);
point1 = new PointF(bounds.X + radius, bounds.Y);
}
else point1 = new PointF(bounds.X, bounds.Y);
// Top side.
if ((RectangleCorners.TopRight & corners) == RectangleCorners.TopRight)
point2 = new PointF(bounds.Right - radius, bounds.Y);
else
point2 = new PointF(bounds.Right, bounds.Y);
path.AddLine(point1, point2);
// Upper right corner.
if ((RectangleCorners.TopRight & corners) == RectangleCorners.TopRight)
{
RectangleF corner = new RectangleF(bounds.Right - diameter, bounds.Y,diameter, diameter);
path.AddArc(corner, 270, 90);
point1 = new PointF(bounds.Right, bounds.Y + radius);
}
else point1 = new PointF(bounds.Right, bounds.Y);
// Right side.
if ((RectangleCorners.BottomRight & corners) == RectangleCorners.BottomRight)
point2 = new PointF(bounds.Right, bounds.Bottom - radius);
else
point2 = new PointF(bounds.Right, bounds.Bottom);
path.AddLine(point1, point2);
// Lower right corner.
if ((RectangleCorners.BottomRight & corners) == RectangleCorners.BottomRight)
{
RectangleF corner = new RectangleF(bounds.Right - diameter,bounds.Bottom - diameter,diameter, diameter);
path.AddArc(corner, 0, 90);
point1 = new PointF(bounds.Right - radius, bounds.Bottom);
}
else point1 = new PointF(bounds.Right, bounds.Bottom);
// Bottom side.
if ((RectangleCorners.BottomLeft & corners) == RectangleCorners.BottomLeft)
point2 = new PointF(bounds.X + radius, bounds.Bottom);
else
point2 = new PointF(bounds.X, bounds.Bottom);
path.AddLine(point1, point2);
// Lower left corner.
if ((RectangleCorners.BottomLeft & corners) == RectangleCorners.BottomLeft)
{
RectangleF corner = new RectangleF(bounds.X, bounds.Bottom - diameter,diameter, diameter);
path.AddArc(corner, 90, 90);
point1 = new PointF(bounds.X, bounds.Bottom - radius);
}
else point1 = new PointF(bounds.X, bounds.Bottom);
// Left side.
if ((RectangleCorners.TopLeft & corners) == RectangleCorners.TopLeft)
point2 = new PointF(bounds.X, bounds.Y + radius);
else
point2 = new PointF(bounds.X, bounds.Y);
path.AddLine(point1, point2);
// Join with the start point.
path.CloseFigure();
return path;
}
}
}
it isn't optimized, it's just prove of concept.
Whole point of this question is to find existing control without need to reinvent the wheel.
If I won't be able to find such control I'll create one and share it.
I have a picturebox that I want the user of my winform to be able to interact with by zooming and dragging the image. Right now that form looks like this
I have the drag and zoom methods implemented. Those look like this.
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
// If the mouse wheel is moved forward (Zoom in)
if (e.Delta > 0)
{
// Change the size of the picturebox, multiply it by the ZOOMFACTOR
pictureBox1.Width = (int)(pictureBox1.Width * 1.25);
pictureBox1.Height = (int)(pictureBox1.Height * 1.25);
// Formula to move the picturebox, to zoom in the point selected by the mouse cursor
pictureBox1.Top = (int)(e.Y - 1.25 * (e.Y - pictureBox1.Top));
pictureBox1.Left = (int)(e.X - 1.25 * (e.X - pictureBox1.Left));
}
else
{
pictureBox1.Width = (int)(pictureBox1.Width / 1.25);
pictureBox1.Height = (int)(pictureBox1.Height / 1.25);
// Formula to move the picturebox, to zoom in the point selected by the mouse cursor
pictureBox1.Top = (int)(e.Y - 0.80 * (e.Y - pictureBox1.Top));
pictureBox1.Left = (int)(e.X - 0.80 * (e.X - pictureBox1.Left));
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
Console.WriteLine("Dragging: false");
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
dragging = true;
xDrag = e.X;
yDrag = e.Y;
Console.WriteLine("Dragging: true");
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Control c = sender as Control;
if (dragging && c != null)
{
c.Top = e.Y + c.Top - yDrag;
c.Left = e.X + c.Left - xDrag;
Console.WriteLine(e.Location.ToString());
}
}
The dragging works fine but the zooming does not work as expected. Instead of zooming in it pushes the image up and to the left as I "zoom in"
Out of curiousity I loaded a bitmap I saved off Google in to test the zoom and it works fine with bitmap images from files; it just doesn't work with images drawn with the Graphics object and I have no idea why. Any help would be greatly appreciated.
Paint event code for picturebox
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
RunEntry entry = this.passedHistory.SelectedItem as RunEntry;
if (entry == null)
{
return;
}
else if(entry.FileRead != null && checkBox1.Checked) //If ANS is selected and show all, get TRE
{
foreach(RunEntry r in passedHistory.Items)
{
if (r.TreComponentRead != null)
{
string ansName = Path.GetFileNameWithoutExtension(entry.FileName);
string treName = Path.GetFileNameWithoutExtension(r.FileName);
if(ansName.Equals(treName, StringComparison.OrdinalIgnoreCase))
{
entry.TreComponentRead = r.TreComponentRead;
}
}
}
}
if (isDraw && entry.FileRead != null)
{
//Preparing to draw
Graphics g = e.Graphics;
g.ScaleTransform(2f, 2f);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.Bicubic;
AnsFile objToDraw = entry.FileRead;
Pen pen = new Pen(Color.Black);
//Getting size of bitmap
int maxWidth = 0, maxHeight = 0;
foreach (AnsJoint joint in objToDraw.AnsJoints)
{
if (joint.Location.X.Length > maxWidth)
{
maxWidth = (int)joint.Location.X.Length;
}
if (joint.Location.Y.Length > maxHeight)
{
maxHeight = (int)joint.Location.Y.Length;
}
}
//Drawing joints //TODO: (Trello: Improve math behind visualizer)
foreach (AnsJoint joint in objToDraw.AnsJoints)
{
PointF jointPoint = this.ToCartesian(new PointF((float)joint.Location.X.Length - 4f, (float)joint.Location.Y.Length + 10f), maxHeight);
e.Graphics.DrawString(joint.JointID.ToString(), new Font(FontFamily.GenericMonospace, 6f, FontStyle.Regular, GraphicsUnit.Point, 1, false), Brushes.Black, jointPoint);
}
//Draw the panels and links //TODO: (Trello: Improve math behind visualizer)
foreach (AnsMember member in objToDraw.AnsMembers)
{
List<AnsPanel> panels = member.Panels; //Drawing the panels
foreach (AnsPanel pan in panels)
{
pen.Color = Color.Red;
PointF p1 = this.ToCartesian(new PointF((float)pan.I.Location.X.Length, (float)pan.I.Location.Y.Length), maxHeight);
PointF p2 = this.ToCartesian(new PointF((float)pan.J.Location.X.Length, (float)pan.J.Location.Y.Length), maxHeight);
g.DrawEllipse(pen, p1.X - 2.5f, p1.Y - 2.5f, 5, 5);
g.DrawEllipse(pen, p2.X - 2.5f, p2.Y - 2.5f, 5, 5);
g.DrawEllipse(pen, p1.X - 3, p1.Y - 3.3f, 5, 5);
g.DrawEllipse(pen, p2.X - 3, p2.Y - 3.3f, 5, 5);
pen.Color = Color.Black;
g.DrawLine(pen, p1, p2);
}
List<AnsLink> links = member.Links; //Drawing the links
foreach (AnsLink link in links)
{
PointF p1 = this.ToCartesian(new PointF((float)link.I.Location.X.Length, (float)link.I.Location.Y.Length), maxHeight);
PointF p2 = this.ToCartesian(new PointF((float)link.J.Location.X.Length, (float)link.J.Location.Y.Length), maxHeight);
g.FillEllipse(Brushes.Green, p1.X - 1.5f, p1.Y - 1.5f, 3, 3);
g.FillEllipse(Brushes.Green, p2.X - 1.5f, p2.Y - 1.5f, 3, 3);
g.DrawLine(pen, p1, p2);
}
}
pictureBox1.Tag = entry.FileName;
}
if (isDraw && entry.TreComponentRead != null)
{
//Preparing to draw
Graphics g = e.Graphics;
g.ScaleTransform(2f, 2f);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.Bicubic;
TreComponent objToDraw = entry.TreComponentRead;
Pen pen = new Pen(Color.Black);
int maxWidth = 0, maxHeight = 0;
foreach (Member member in objToDraw.Members)
{
foreach (GeometryClassLibrary.Point p in member.Geometry.Vertices)
{
if (p.X.Inches > maxWidth)
{
maxWidth = (int)p.X.Inches;
}
if (p.Y.Inches > maxHeight)
{
maxHeight = (int)p.Y.Inches;
}
}
}
maxHeight += 5; maxWidth += 5;
maxHeight += 15; maxWidth += 5;
foreach (Member member in objToDraw.Members)
{
List<PointF> pointsToDraw = new List<PointF>();
foreach (GeometryClassLibrary.Point p in member.Geometry.Vertices)
{
pointsToDraw.Add(ToCartesian(new PointF((float)p.X.Inches, (float)p.Y.Inches), maxHeight));
PointF pointToDraw = this.ToCartesian(new PointF((float)p.X.Inches, (float)p.Y.Inches), maxHeight);
g.FillEllipse(Brushes.Red, pointToDraw.X - 1.5f, pointToDraw.Y - 1.5f, 3, 3);
pointsToDraw.Add(pointToDraw);
}
g.DrawPolygon(pen, pointsToDraw.ToArray());
//Getting center of member and labeling member
float totalX = 0, totalY = 0;
foreach (PointF p in pointsToDraw)
{
totalX += p.X;
totalY += p.Y;
}
float centerX = totalX / pointsToDraw.Count;
float centerY = totalY / pointsToDraw.Count - 10;
PointF midPoint = new PointF(centerX, centerY);
g.DrawString(member.Name, new Font(FontFamily.GenericMonospace, 6f, FontStyle.Regular, GraphicsUnit.Point, 1, false), Brushes.Black, midPoint);
}
pictureBox1.Tag = entry.FileName;
}
}
I am having trouble drawing graphics on a simple form. My code compiles and runs, but the intended red box does not show up.
I am using the full .NET Framework 4 in Visual Studio 2010.
What is going wrong, and how can it be fixed?
private void Form1_Load(object sender, EventArgs e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
graphicsObj.DrawRectangle(myPen, myRectangle);
}
EDIT: Working But Slow Code
void BatteryPaint(object sender, EventArgs e)
{
TabPage page = (TabPage)sender;
if (!controlsSetup)
{
populateBatteryTab(page);
controlsSetup = true;
}
//Create the items
Rectangle busBar = new Rectangle();
Rectangle batPack = new Rectangle();
Rectangle pack1Outline = new Rectangle();
Rectangle pack2Outline = new Rectangle();
Rectangle pack3Outline = new Rectangle();
Rectangle pack4Outline = new Rectangle();
Color GreenZone = Color.FromArgb(150, 0, 255, 0);
Color YellowZone = Color.FromArgb(150, 255, 255, 0);
Color RedZone = Color.FromArgb(150, 255, 0, 0);
Color greyZone = Color.FromArgb(200, 200, 200, 200);
Graphics graphicControl = page.CreateGraphics();
SolidBrush busBarBrush = new SolidBrush(Color.Peru);
SolidBrush GreenBrush = new SolidBrush(GreenZone);
SolidBrush GreyBrush = new SolidBrush(greyZone);
Pen packPen = new Pen(Color.LightGray, (float)8);
Point busBarTop = new Point(page.Width / 64, page.Height / 32);
Point busBarBottom = new Point(busBarTop.X, busBarTop.Y + page.Height / 6);
//change the properties
//Bus Bar Top
busBar.Width = page.Width*153 / 640;
busBar.Height = page.Height / 64;
busBar.Location = busBarTop;
graphicControl.FillRectangle(busBarBrush, busBar);
//Bus Bar Bottom
busBar.Location = busBarBottom;
graphicControl.FillRectangle(busBarBrush, busBar);
//Pack 1
batPack.Width = page.Width / 20;
batPack.Height = (busBarBottom.Y + busBar.Height) - busBarTop.Y;
batPack.Location = new Point(busBarTop.X + page.Width / packSpacingMultiplier, busBarTop.Y);
pack1Outline.Width = batOutlineWidth;
graphicControl.FillRectangle(GreenBrush, batPack);
pack1Outline.Height = (3 * (Battery.Width + page.Width / batSpacingMultiplier) + page.Width / batSpacingMultiplier);
pack1Outline.Location = new Point(BatPack1.X - (page.Width / batSpacingMultiplier), BatPack1.Y - (page.Width / batSpacingMultiplier));
for(int numBats = 0; numBats < 30; numBats++)
{
Battery.Location = new Point(BatPack1.X + ((numBats % 10) * (Battery.Width + page.Width / batSpacingMultiplier)), BatPack1.Y + ((numBats / 10) * (Battery.Width + page.Width / batSpacingMultiplier)));
graphicControl.FillEllipse(new SolidBrush(BatteryZone(0.00)), Battery);
}
//Pack 2
batPack.Location = new Point(batPack.Location.X + batPack.Width + page.Width / packSpacingMultiplier, batPack.Location.Y);
graphicControl.FillRectangle(GreenBrush, batPack);
pack2Outline.Width = batOutlineWidth;
pack2Outline.Height = (3 * (Battery.Width + page.Width / batSpacingMultiplier) + page.Width / batSpacingMultiplier);
pack2Outline.Location = new Point(BatPack2.X - (page.Width / batSpacingMultiplier), BatPack2.Y - (page.Width / batSpacingMultiplier));
for(int numBats = 0; numBats < 30; numBats++)
{
Battery.Location = new Point(BatPack2.X + ((numBats % 10) * (Battery.Width + page.Width / batSpacingMultiplier)), BatPack2.Y + ((numBats / 10) * (Battery.Width + page.Width / batSpacingMultiplier)));
graphicControl.FillEllipse(new SolidBrush(BatteryZone(0.00)), Battery);
}
//Pack 3
batPack.Location = new Point(batPack.Location.X + batPack.Width + page.Width / packSpacingMultiplier, batPack.Location.Y);
graphicControl.FillRectangle(GreenBrush, batPack);
pack3Outline.Width = batOutlineWidth;
pack3Outline.Height = (3 * (Battery.Width + page.Width / batSpacingMultiplier) + page.Width / batSpacingMultiplier);
pack3Outline.Location = new Point(BatPack3.X - (page.Width / batSpacingMultiplier), BatPack3.Y - (page.Width / batSpacingMultiplier));
for(int numBats = 0; numBats < 30; numBats++)
{
Battery.Location = new Point(BatPack3.X + ((numBats % 10) * (Battery.Width + page.Width / batSpacingMultiplier)), BatPack3.Y + ((numBats / 10) * (Battery.Width + page.Width / batSpacingMultiplier)));
graphicControl.FillEllipse(new SolidBrush(BatteryZone(0.00)), Battery);
}
//Pack 4
batPack.Location = new Point(batPack.Location.X + batPack.Width + page.Width / packSpacingMultiplier, batPack.Location.Y);
graphicControl.FillRectangle(GreyBrush, batPack);
pack4Outline.Width = batOutlineWidth;
pack4Outline.Height = (3 * (Battery.Width + page.Width / batSpacingMultiplier) + page.Width / batSpacingMultiplier);
pack4Outline.Location = new Point(BatPack4.X - (page.Width / batSpacingMultiplier), BatPack4.Y - (page.Width / batSpacingMultiplier));
for(int numBats = 0; numBats < 30; numBats++)
{
Battery.Location = new Point(BatPack4.X + ((numBats % 10) * (Battery.Width + page.Width / batSpacingMultiplier)), BatPack4.Y + ((numBats / 10) * (Battery.Width + page.Width / batSpacingMultiplier)));
graphicControl.FillEllipse(new SolidBrush(BatteryZone(0.00)), Battery);
}
//add the controls
graphicControl.DrawRectangle(packPen, pack1Outline);
graphicControl.DrawRectangle(packPen, pack2Outline);
graphicControl.DrawRectangle(packPen, pack3Outline);
graphicControl.DrawRectangle(packPen, pack4Outline);
}
You shouldn't do your drawing in the Load event, which is fired before your form is even displayed for the first time. The window is repainted when it is displayed, which clears the graphics you've drawn. If you want a persistent rectangle, handle the Paint event instead:
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics graphicsObj = e.Graphics;
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
graphicsObj.DrawRectangle(myPen, myRectangle);
}
If you don't want a persistent rectangle (highly doubtful, but still possible), try handling the Shown event instead of the Load event.
If the graphics displayed will be updated frequently (e.g. in a game), make sure to set DoubleBuffered to true and override OnPaint instead of handling an event:
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen myPen = new Pen(Color.Red, 5);
g.DrawRectangle(myPen, 20, 20, 250, 200);
}
I have been trying to draw an annulus (ring with thickness) with a transparent hole and a gradient rim in C# with very little success. Does anyone have any suggestions on how to do this?
here's a nice Blend Utility
Here's the Final result - thanks to BlueMonkMN
Rectangle GetSquareRec(double radius, int x, int y)
{
double r = radius;
double side = Math.Sqrt(Math.Pow(r, 2) / 2);
Rectangle rec = new Rectangle(x - ((int)side), y - ((int)side), (int)(side * 2) + x, (int)(side * 2) + y);
return rec;
}
void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics gTarget = e.Graphics;
gTarget.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath pTemp = new GraphicsPath();
Rectangle r = GetSquareRec(200, 225, 225);
pTemp.AddEllipse(r);
pTemp.AddEllipse(GetSquareRec(50, 225, 225));
Color[] colors = new Color[5];
colors[0] = Color.FromArgb(192, 192, 192);
colors[1] = Color.FromArgb(105, 0, 0);
colors[2] = Color.FromArgb(169, 169, 169);
colors[3] = Color.FromArgb(0, 0, 0);
colors[4] = Color.FromArgb(0, 0, 0);
float[] positions = new float[5];
positions[0] = 0f;
positions[1] = 0.1f;
positions[2] = 0.35f;
positions[3] = 0.5f;
positions[4] = 1f;
ColorBlend Cb = new ColorBlend();
Cb.Colors = colors;
Cb.Positions = positions;
PathGradientBrush pgb = new PathGradientBrush(pTemp);
pgb.InterpolationColors = Cb;
pgb.CenterPoint = new PointF(r.X + (r.Width / 2), r.Y + (r.Height / 2));
gTarget.FillPath(pgb, pTemp);
}
http://www.freeimagehosting.net/uploads/th.515733e62e.jpg
This is how I did it in the Scrolling Game Development Kit:
pTemp = new GraphicsPath();
pTemp.AddEllipse(Start.X, Start.Y, End.X - Start.X, End.Y - Start.Y);
pTemp.AddEllipse((Start.X * 3 + End.X) / 4f,
(Start.Y * 3 + End.Y) / 4f,
(End.X - Start.X) / 2f,
(End.Y - Start.Y) / 2f);
PathGradientBrush pgb = new PathGradientBrush(pTemp);
Blend b = new Blend();
b.Factors = new float[] { 0, 1, 1 };
b.Positions = new float[] { 0, .5F, 1 };
pgb.Blend = b;
pgb.CenterColor = ((SolidBrush)CurrentBrush).Color;
pgb.SurroundColors = new Color[] {CurrentPen.Color};
gTarget.FillPath(pgb, pTemp);
pgb.Dispose();
pTemp.Dispose();
(source: enigmadream.com)
I edited the original SGDK code for this sample because originally I wasn't smart enough to scale the gradient to exclude the hole, but now I guess I am :).
If you would rather see the gradient like this:
(source: enigmadream.com)
Then change the blend code to look like this:
Blend blend = new Blend();
blend.Factors = new float[] { 0, 1, 0, 0 };
blend.Positions = new float[] { 0, 0.25F, .5F, 1 };
pgb.Blend = blend;
You may use two calls to Graphics.DrawArc combined, drawing the top and bottom or left and right portions of the annulus, one portion at a time.