Smooth curves in button - c#

I want to create a toggle button similar to this or to this. Animation does not matter to me. I tried to create a toggle button with the code below. However I cannot get it to be smooth curves and edges. I am using windows forms application and a total beginner in C# UI design.
My question is that is it possible to make the curves smooth, or it will still stay like this? I imported the code in the second link, but still the button did not appear smooth.
I also used -
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
Here is full code for the button -
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace MyWorkspace
{
public class ToggleButton : Control
{
#region variables
public enum ButtonState { ON, OFF };
private ButtonState toggleState = ButtonState.OFF;
private Rectangle contentRectangle = Rectangle.Empty;
#endregion
#region properties
public ButtonState ToggleState
{
get
{
return toggleState;
}
set
{
if (toggleState != value)
{
toggleState = value;
Invalidate();
this.Refresh();
}
}
}
#endregion
public ToggleButton() : base()
{
this.MinimumSize = new Size(50, 25);
this.MaximumSize = new Size(50, 25);
contentRectangle = new Rectangle(0, 0, this.Width, this.Height);
this.BackColor = Application.RenderWithVisualStyles ? Color.Azure : this.Parent.BackColor;
}
// Draw the large or small button, depending on the current state.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(0, contentRectangle.Y, contentRectangle.Height, contentRectangle.Height);
GraphicsPath gp = new GraphicsPath();
int d = this.Height;
gp.AddArc(contentRectangle.X, contentRectangle.Y, d, d, 180, 90);
gp.AddArc(contentRectangle.X + contentRectangle.Width - d, contentRectangle.Y, d, d, 270, 90);
gp.AddArc(contentRectangle.X + contentRectangle.Width - d, contentRectangle.Y + contentRectangle.Height - d, d, d, 0, 90);
gp.AddArc(contentRectangle.X, contentRectangle.Y + contentRectangle.Height - d, d, d, 90, 90);
this.Region = new Region(gp);
Rectangle ar2 = new Rectangle(rect.X, contentRectangle.Y, (rect.X + rect.Width / 2) + contentRectangle.Right, contentRectangle.Height);
LinearGradientBrush br;
Rectangle ellipse_rect;
if (toggleState == ButtonState.ON)
{
br = new LinearGradientBrush(ar2, Color.FromArgb(0, 127, 234), Color.FromArgb(96, 174, 241), LinearGradientMode.Vertical);
ellipse_rect = new Rectangle(contentRectangle.Right - (contentRectangle.Height -2),
contentRectangle.Y, contentRectangle.Height - 4, contentRectangle.Height);
}
else
{
br = new LinearGradientBrush(ar2, Color.FromArgb(120, 120, 120), Color.Silver, LinearGradientMode.Vertical);
ellipse_rect = rect;
}
e.Graphics.FillRectangle(br, ar2);
e.Graphics.DrawEllipse(new Pen(Color.Gray, 2f), ellipse_rect);
LinearGradientBrush br2 = new LinearGradientBrush(rect, Color.White, Color.Silver, LinearGradientMode.Vertical);
e.Graphics.FillEllipse(br2, ellipse_rect);
Color c = this.Parent != null ? this.Parent.BackColor : Color.White;
e.Graphics.DrawPath(new Pen(c, 2f), gp);
}
protected override void OnClick(EventArgs e)
{
if (toggleState == ButtonState.ON)
toggleState = ButtonState.OFF;
else
toggleState = ButtonState.ON;
Invalidate();
}
}
}

Please post an image of what your solution looks like, but from what you have described I would guess you do not have anti-aliasing enabled. Here is a MSDN article about how to enable anti-aliasing. If you are going to be changing the look of many controls in your application, you may want to look into Windows Presentation Foundation or the new Universal Windows Platform.
In contrast to Windows Forms, both WPF and UWP are vector based interface layers that are designed using XAML. Because of the way WPF and UWP implement their designing system, it is very easy to completely customize the look and feel of your application. In addition both platforms have built in functionality for animations.

Related

Transparent Overlapping Circular Progress Bars (Custom Control)

I am having some trouble with a custom circular progress bar control. I am trying to overlap the two of them at the lower right corner. It has a transparent background, which obviously in WinForms is showing the background, but has no effect on each other.
Here is what I am seeing:
I have been researching on stackoverflow, and have found a few answers to people having this issue with custom picturebox controls. Most of the solutions, seem to have no effect on the circular progress bar control. Some of the solutions I have tried is.
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20;
return cp;
}
}
I also have the code on the custom control for allowing transparent backgrounds. Obviously, as I stated, this does not effect overlapping controls.
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
There is also a TransparentControl solution on stackoverflow which I saw people using. I have created the control, but either have no idea how to use it, or it doesn't work in my situation. Here is the code from that control.
public class TransparentControl : Panel
{
public bool drag = false;
public bool enab = false;
private int m_opacity = 100;
private int alpha;
public TransparentControl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
this.BackColor = Color.Transparent;
}
public int Opacity
{
get
{
if (m_opacity > 100)
{
m_opacity = 100;
}
else if (m_opacity < 1)
{
m_opacity = 1;
}
return this.m_opacity;
}
set
{
this.m_opacity = value;
if (this.Parent != null)
{
Parent.Invalidate(this.Bounds, true);
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x20;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle bounds = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
Color frmColor = this.Parent.BackColor;
Brush bckColor = default(Brush);
alpha = (m_opacity * 255) / 100;
if (drag)
{
Color dragBckColor = default(Color);
if (BackColor != Color.Transparent)
{
int Rb = BackColor.R * alpha / 255 + frmColor.R * (255 - alpha) / 255;
int Gb = BackColor.G * alpha / 255 + frmColor.G * (255 - alpha) / 255;
int Bb = BackColor.B * alpha / 255 + frmColor.B * (255 - alpha) / 255;
dragBckColor = Color.FromArgb(Rb, Gb, Bb);
}
else
{
dragBckColor = frmColor;
}
alpha = 255;
bckColor = new SolidBrush(Color.FromArgb(alpha, dragBckColor));
}
else
{
bckColor = new SolidBrush(Color.FromArgb(alpha, this.BackColor));
}
if (this.BackColor != Color.Transparent | drag)
{
g.FillRectangle(bckColor, bounds);
}
bckColor.Dispose();
g.Dispose();
base.OnPaint(e);
}
protected override void OnBackColorChanged(EventArgs e)
{
if (this.Parent != null)
{
Parent.Invalidate(this.Bounds, true);
}
base.OnBackColorChanged(e);
}
protected override void OnParentBackColorChanged(EventArgs e)
{
this.Invalidate();
base.OnParentBackColorChanged(e);
}
}
Any assistance would be appreciated. This has been driving me nuts for hours. Thanks :)
UPDATE 1: I tried using the following code snippet from examples posted below. This yielded the same results. I still have that blank space between the circular progress bars (as seen in the picture).
Parent.Controls.Cast<Control>()
.Where(c => Parent.Controls.GetChildIndex(c) > Parent.Controls.GetChildIndex(this))
.Where(c => c.Bounds.IntersectsWith(this.Bounds))
.OrderByDescending(c => Parent.Controls.GetChildIndex(c))
.ToList()
.ForEach(c => c.DrawToBitmap(bmp, c.Bounds));
Still stumped. :(
UPDATE 2: I tried setting the front circularprogressbar to use the back circularprogressbar as it's parent in the FormLoad. That didn't work out either. It made them transparent to each other, but cut off any part of the top circularprogressbar that wasn't within' the boundaries of the back.
var pts = this.PointToScreen(circularprogressbar1.Location);
pts = circularprogressbar2.PointToClient(pts);
circularprogressbar1.Parent = circularprogressbar2;
circularprogressbar1.Location = pts;
I'm going to give you just a couple of suggestions on how to proceed.
Start off with this bare-bones transparent control (TransparentPanel).
This class is derived from Panel. That's the first choice to make: is Panel the right control to inherit from/extend for this task? Maybe it is, maybe not.
For example, a Panel is a container. Do you need the features of a container, here? Container means a lot. It inherits ScrollableControl and has ContainerControl among its Window styles. It comes with a baggage already.
You could opt for a Label instead, it's light-weight. Or build a UserControl.
I don't think there's an absolute best choice. It depends of what this custom control is used for. You need to try it out.
Note:
To create the rotation effect with the code shown here, you need the TransparentPanel Control shown below, it won't work the same way drawing on the surface of a standard Control.
This Control generates sort of a persistence in the drawn shapes, which won't exist using another type of Control as canvas (not without tweaking it heavily, that is).
class TransparentPanel : Panel
{
internal const int WS_EX_TRANSPARENT = 0x00000020;
public TransparentPanel() => InitializeComponent();
protected void InitializeComponent()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.Opaque |
ControlStyles.ResizeRedraw |
ControlStyles.SupportsTransparentBackColor |
ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
}
protected override CreateParams CreateParams
{
get {
var cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
}
Other notes:
Here, ControlStyles.SupportsTransparentBackColor is set explicitly. The Panel class already supports this. It's specified anyway because it gives the idea of what this custom control is for just reading at its constructor.
Also, ControlStyles.OptimizedDoubleBuffer is set to false.
This prevents the System to interfere in any way with the painting of the control. There's no caching, the Custom Control is painted new when it's Invalidated. The container Form should preferably have its DoubleBuffer property set to true, but you might want test it without, to see if there's a difference.
This Custom Control (not to be confused with a UserControl) is completely transparent. It doesn't draw its background. But you can paint anything on its surface.
Take the links posted before:
This Translucent Label (no BackGround painting, disabled DoubleDuffering)
Reza Aghaei's transparent Panel (using Opacity in a different way)
TaW's Grid Panel (Color.Transparent and DoubleBuffer)
These notes: Reasons for why a WinForms label does not want to be transparent?
4 different ways to get to the same result. Which one to choose depends on the context/destination.
A design-time advice: when you are testing a custom control functionalities, remember to always rebuild the project. It can happen that a CustomControl, droppen on a Form from the Toolbox, is not updated with the new changes when the project is run.
Also, if you add or remove properties, you need to delete the control, rebuild and drop a new one on the Form.
If you don't, there's a really good chance that your modification/addition are completely ignored and you keep on testing features that never get into play.
An example, using 2 overlapping custom controls.
(using the bare-bones custom TransparentPanel)
This is the test code used to generate these drawings:
Create a new Custom Control using the TransparentPanel class shown before:
Drop two TransparentPanel objects on a test Form
Assign to TransparentPanel1 and TransparentPanel2 the transparentPanel1_Paint and transparentPanel2_Paint event handlers.
Overlap the two transparent Panels, making sure you don't nest them by mistake.
Adapt the rest of the code (you need just a Button, here named btnRotate, assign the btnRotate_Click handler)
private System.Windows.Forms.Timer RotateTimer = null;
private float RotationAngle1 = 90F;
private float RotationAngle2 = 0F;
public bool RotateFigures = false;
public form1()
{
InitializeComponent();
RotateTimer = new Timer();
RotateTimer.Interval = 50;
RotateTimer.Enabled = false;
RotateTimer.Tick += new EventHandler(this.RotateTick);
}
protected void RotateTick(object sender, EventArgs e)
{
RotationAngle1 += 10F;
RotationAngle2 += 10F;
transparentPanel1.Invalidate();
transparentPanel2.Invalidate();
}
private void btnRotate_Click(object sender, EventArgs e)
{
RotateTimer.Enabled = !RotateTimer.Enabled;
if (RotateTimer.Enabled == false)
{
RotateFigures = false;
RotationAngle1 = 90F;
RotationAngle2 = 0F;
}
else
{
RotateFigures = true;
}
}
private void transparentPanel1_Paint(object sender, PaintEventArgs e)
{
if (!RotateFigures) return;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
e.Graphics.CompositingMode = CompositingMode.SourceOver;
Rectangle rect = transparentPanel1.ClientRectangle;
Rectangle rectInner = rect;
using (Pen transpPen = new Pen(transparentPanel1.Parent.BackColor, 10))
using (Pen penOuter = new Pen(Color.SteelBlue, 8))
using (Pen penInner = new Pen(Color.Teal, 8))
using (Matrix m1 = new Matrix())
using (Matrix m2 = new Matrix())
{
m1.RotateAt(-RotationAngle1, new PointF(rect.Width / 2, rect.Height / 2));
m2.RotateAt(RotationAngle1, new PointF(rect.Width / 2, rect.Height / 2));
rect.Inflate(-(int)penOuter.Width, -(int)penOuter.Width);
rectInner.Inflate(-(int)penOuter.Width * 3, -(int)penOuter.Width * 3);
e.Graphics.Transform = m1;
e.Graphics.DrawArc(transpPen, rect, -4, 94);
e.Graphics.DrawArc(penOuter, rect, -90, 90);
e.Graphics.ResetTransform();
e.Graphics.Transform = m2;
e.Graphics.DrawArc(transpPen, rectInner, 190, 100);
e.Graphics.DrawArc(penInner, rectInner, 180, 90);
}
}
private void transparentPanel2_Paint(object sender, PaintEventArgs e)
{
if (!RotateFigures) return;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
e.Graphics.CompositingMode = CompositingMode.SourceOver;
Rectangle rect = transparentPanel2.ClientRectangle;
Rectangle rectInner = rect;
using (Pen transpPen = new Pen(transparentPanel2.Parent.BackColor, 10))
using (Pen penOuter = new Pen(Color.Orange, 8))
using (Pen penInner = new Pen(Color.DarkRed, 8))
using (Matrix m1 = new Matrix())
using (Matrix m2 = new Matrix())
{
m1.RotateAt(RotationAngle2, new PointF(rect.Width / 2, rect.Height / 2));
m2.RotateAt(-RotationAngle2, new PointF(rect.Width / 2, rect.Height / 2));
rect.Inflate(-(int)penOuter.Width, -(int)penOuter.Width);
rectInner.Inflate(-(int)penOuter.Width * 3, -(int)penOuter.Width * 3);
e.Graphics.Transform = m1;
e.Graphics.DrawArc(transpPen, rect, -4, 94);
e.Graphics.DrawArc(penOuter, rect, 0, 90);
e.Graphics.ResetTransform();
e.Graphics.Transform = m2;
e.Graphics.DrawArc(transpPen, rectInner, 190, 100);
e.Graphics.DrawArc(penInner, rectInner, 180, 90);
}
}

How to make a rounded textbox in C# WinForms?

I already made a rounded button and now im trying to create a rounded textbox. I searched some questions but all is in VB and I don't know that language. And converters are weird. So I tried creating a rounded textbox. So I set the UserPaint to true so I can use OnPaint. It works beautifully on my buttons but it glitches out on my textboxes. It has 2 issues:
The font size is always the same size no matter what I set it to.
And when onpaint is called but the text doesn't change it deletes it. That is mostly when I hover my mouse over it.
Code:
class RoundedTextBox : TextBox
{
public Color color = Color.White;
public int borderRadius = 25;
public RoundedTextBox()
{
SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
RectangleF Rect = new RectangleF(0, 0, this.Width, this.Height);
SolidBrush brush = new SolidBrush(color);
GraphicsPath GraphPath = Functions.FillRoundedRectangle(e.Graphics, brush, Rect, borderRadius);
this.Region = new Region(GraphPath);
}
}
How I add my textbox:
RoundedTextBox usernameTextbox = new RoundedTextBox();
usernameTextbox.Location = new Point(14, 217);
usernameTextbox.Font = new Font(usernameTextbox.Font.FontFamily, 20);
usernameTextbox.Size = new Size(282, this.Height);
usernameTextbox.color = Color.White;
usernameTextbox.Name = "usernameTextbox";
usernameTextbox.Text = "test";
textboxes.Add(usernameTextbox);
usernameTextbox.BackColor = Color.White;
usernameTextbox.borderRadius = 20;
this.Controls.Add(usernameTextbox);
Gif of the problem

Toggle switch control in Windows Forms

I am designing a toggle switch control using CheckBox, but currently my control only draws a circle. How can I draw round shapes like the below image and how can I change the location of the circle based on the value of the control to represent checked and unchecked states like the below image?
Here is my code:
public class MyCheckBox:CheckBox
{
public MyCheckBox()
{
this.Appearance = System.Windows.Forms.Appearance.Button;
this.BackColor = Color.Transparent;
this.TextAlign = ContentAlignment.MiddleCenter;
this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.FlatAppearance.BorderColor = Color.RoyalBlue;
this.FlatAppearance.BorderSize = 2;
}
protected override void OnPaint(PaintEventArgs e)
{
this.OnPaintBackground(e);
using (var path = new GraphicsPath())
{
var c = e.Graphics.ClipBounds;
var r = this.ClientRectangle;
r.Inflate(-FlatAppearance.BorderSize, -FlatAppearance.BorderSize);
path.AddEllipse(r);
e.Graphics.SetClip(path);
base.OnPaint(e);
e.Graphics.SetClip(c);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if (this.Checked)
{
using (var p = new Pen(FlatAppearance.BorderColor,
FlatAppearance.BorderSize))
{
e.Graphics.DrawEllipse(p, r);
}
}
}
}
}
I know this is a Windows Forms question. But you may want to take a look at Toggle Switches or read more about Universal Windows App Components.
Anyway, here is an answer for Windows Forms developers. It shows how we can customize rendering of a checkbox to have such appearance.
Currently you are drawing only an ellipse, and it's quite a toggle button. But if you want to show it like the below image, you should first draw a round shape for background, and then based on the Checked value, draw the check circle. Using the code in Example part of the answer you can have a CheckBox with such a UI:
Example
The important thing about this sample is it's completely a CheckBox control and supports check using mouse and keyboard. It also supports data-binding and all other standard features of CheckBox. The code is not perfect, but it is a good start point to have a yes/no toggle switch:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class MyCheckBox : CheckBox
{
public MyCheckBox()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
Padding = new Padding(6);
}
protected override void OnPaint(PaintEventArgs e)
{
this.OnPaintBackground(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (var path = new GraphicsPath())
{
var d = Padding.All;
var r = this.Height - 2 * d;
path.AddArc(d, d, r, r, 90, 180);
path.AddArc(this.Width - r - d, d, r, r, -90, 180);
path.CloseFigure();
e.Graphics.FillPath(Checked ? Brushes.DarkGray : Brushes.LightGray, path);
r = Height - 1;
var rect = Checked ? new Rectangle(Width - r - 1, 0, r, r)
: new Rectangle(0, 0, r, r);
e.Graphics.FillEllipse(Checked ? Brushes.Green : Brushes.WhiteSmoke, rect);
}
}
}

Enhanced crosshair cursor possible?

I have found this question (as a few others), but this is the one I have implemented so far:
Crosshair cursor with additional lines in C#
As it states, I can use a stock cursor "cross" directly in the IDE. This is a really good way to do things. The answer specified in the answer above draws a cross on the screen at the given width / height. Eg:
private Cursor crossCursor(Pen pen, Brush brush, int x, int y)
{
var pic = new Bitmap(x, y);
Graphics gr = Graphics.FromImage(pic);
var pathX = new GraphicsPath();
var pathY = new GraphicsPath();
pathX.AddLine(0, y / 2, x, y / 2);
pathY.AddLine(x / 2, 0, x / 2, y);
gr.DrawPath(pen, pathX);
gr.DrawPath(pen, pathY);
IntPtr ptr = pic.GetHicon();
var c = new Cursor(ptr);
return c;
}
My issue is that I want my cross hairs to extend to the Bounds of the viewing area. To provide context here, I have:
//Form
//TableLayoutPanel
//UserControl (fills the TableLayoutPanel visible area)
So how can I adjust my cursor so that the lines extend (much like in CAD pacakages)?
Thanks.
Update: I have tried calling the method from here:
protected override void OnLoad(System.EventArgs e)
{
Cursor = crossCursor(Pens.WhiteSmoke, Brushes.WhiteSmoke, Bounds.Width, Bounds.Height);
}
But it is not Ok because at this point in time Bounds is returning a dimension of 150 by 150 which is not the size of the TableLayoutPanel.
Update: I have adjuted it to use the Resize handler instead and it does improve things:
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Cursor = crossCursor(Pens.WhiteSmoke, Brushes.WhiteSmoke, Bounds.Width, Bounds.Height);
}
The only problem now (and it kind of makes sense I suppose) is that the cursor will only take the full width and height of the view when it is central to the view. As soon as I move about in the view that cursor does not adjust. I always want a horizontal/vertical line through the mouse position (not just the initial cross).
See:
The crosshairs need extending (the thicker red lines). Either I need to constantly create the cursor as the mouse moves or construct the two lines another way. What to do?
I came across this:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/7bdbad6d-1f65-461b-8f0c-6ef4f243fa6b/crosshair-cursor-using-c?forum=csharpgeneral
So, instead of changing the cursor object I now draw lines in the controls MouseMove handler:
Region r = new Region();
r.Union(new Rectangle(0, lastY, this.Width, 1));
r.Union(new Rectangle(lastX, 0, 1, this.Height));
this.Invalidate(r);
this.Update();
Graphics g = Graphics.FromHwnd(this.Handle);
g.DrawLine(Pens.White, 0, e.Y, this.Width, e.Y);
g.DrawLine(Pens.White, e.X, 0, e.X, this.Height);
int intDiameter = 20;//the diameter of this circle
g.DrawEllipse(Pens.White, e.X - intDiameter / 2, e.Y - intDiameter / 2, 20, 20);
//to draw the circle
lastX = e.X;
lastY = e.Y;
It works, but I get noticiable screen flicker doing it this way.
You don't need to create a cursor. You can create a double buffered control and draw cross over control.
using System;
using System.Drawing;
using System.Windows.Forms;
public class DrawingSurface : Control
{
Pen crossPen;
Pen rectanglePen;
Brush rectangleBrush;
public DrawingSurface()
{
this.DoubleBuffered = true;
this.ResizeRedraw = true;
crossPen = new Pen(Color.Red, 2);
rectangleBrush = new SolidBrush(Color.FromArgb(50, Color.Blue));
rectanglePen = new Pen(Color.Blue, 1);
}
bool mouseDown = false;
Point startPoint = Point.Empty;
Point endPoint = Point.Empty;
protected override void OnMouseDown(MouseEventArgs e)
{
startPoint = e.Location;
mouseDown = true;
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
mouseDown = false;
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
endPoint = e.Location;
this.Invalidate();
base.OnMouseMove(e);
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
if (this.ClientRectangle.Contains(endPoint))
DrawCross(e.Graphics, endPoint);
if (mouseDown)
DrawRectangle(e.Graphics, startPoint, endPoint);
}
void DrawCross(Graphics g, Point point)
{
g.DrawLine(crossPen, new Point(0, point.Y), new Point(Width, point.Y));
g.DrawLine(crossPen, new Point(point.X, 0), new Point(point.X, Height));
}
void DrawRectangle(Graphics g, Point point1, Point point2)
{
var rectangle = new Rectangle(
Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y),
Math.Abs(point1.X - point2.X), Math.Abs(point1.Y - point2.Y));
g.FillRectangle(rectangleBrush, rectangle);
g.DrawRectangle(rectanglePen, rectangle);
}
protected override void Dispose(bool disposing)
{
crossPen.Dispose();
rectanglePen.Dispose();
rectangleBrush.Dispose();
base.Dispose(disposing);
}
}

CSS3-like box shadow implementation / algorithm

I am looking for or trying to implement an algorithm to draw box shadows (as in the CSS 3 specifiction) which accepts the following parameters:
Horizontal Offset
Vertical Offset
Inset
Spread
Blur
Color
(Optional: Opacity).
Where to start.
I have looked for Firefox / Chrome source code to see if I can pull an implementation from there, no such luck!
I have looked into linear gradient algorithms, drawing them with a box, which kind of works, except with rounded rectangles it leaves empty pixels in the shadow, presumably due to the radius of the edge.
I am doing this in .NET with GDI+. My aim is NOT to create drop shadows for images. I have already seen articles on this. I want to create drop shadows for shapes drawn with GDI+.
Any help appreciated!
I coded for you a DropShadowPanel that handles controls inside it and adds the shadows (outer or inner) as required by the Tag of the control.
As you can see in the image controls get their shadows as defined:
tags:
textbox: DropShadow:5,5,5,10,#000000,noinset
calendar: DropShadow:10,10,80,30,#0000FF,noinset
picturebox top left: DropShadow:-50,20,50,10,#888888,noinset
picturebox bottom left: DropShadow:10,10,20,20,#442200,inset
picturebox lower right: DropShadow:0,0,50,50,#442200,noinset
Here is the code for the Panel:
(it uses intermediate drawings into an image before drawing to the control gdi object, to not make the form crawl - this actually works pretty fast)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public class DropShadowPanel : Panel
{
protected override void OnControlAdded(ControlEventArgs e)
{
e.Control.Paint += new PaintEventHandler(Control_Paint);
base.OnControlAdded(e);
}
void Control_Paint(object sender, PaintEventArgs e)
{
CheckDrawInnerShadow(sender as Control, e.Graphics);
}
private void CheckDrawInnerShadow(Control sender, Graphics g)
{
var dropShadowStruct = GetDropShadowStruct(sender);
if (dropShadowStruct == null || !dropShadowStruct.Inset)
{
return;
}
DrawInsetShadow(sender as Control, g);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
e.Control.Paint -= new PaintEventHandler(Control_Paint);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawShadow(Controls.OfType<Control>().Where(c => c.Tag != null && c.Tag.ToString().StartsWith("DropShadow")), e.Graphics);
}
void DrawInsetShadow(Control control, Graphics g)
{
var dropShadowStruct = GetDropShadowStruct(control);
var rInner = new Rectangle(Point.Empty, control.Size);
var img = new Bitmap(rInner.Width, rInner.Height, g);
var g2 = Graphics.FromImage(img);
g2.CompositingMode = CompositingMode.SourceCopy;
g2.FillRectangle(new SolidBrush(dropShadowStruct.Color), 0, 0, control.Width, control.Height);
rInner.Offset(dropShadowStruct.HShadow, dropShadowStruct.VShadow);
rInner.Inflate(dropShadowStruct.Blur, dropShadowStruct.Blur);
rInner.Inflate(-dropShadowStruct.Spread, -dropShadowStruct.Spread);
double blurSize = dropShadowStruct.Blur;
double blurStartSize = blurSize;
do
{
var transparency = blurSize/blurStartSize;
var color = Color.FromArgb(((int)(255 * (transparency * transparency))), dropShadowStruct.Color);
rInner.Inflate(-1,-1);
DrawRoundedRectangle(g2, rInner, (int)blurSize, Pens.Transparent, color);
blurSize--;
} while (blurSize > 0);
g.DrawImage(img, 0, 0);
g.Flush();
g2.Dispose();
img.Dispose();
}
void DrawShadow(IEnumerable<Control> controls, Graphics g)
{
foreach (var control in controls)
{
var dropShadowStruct = GetDropShadowStruct(control);
if (dropShadowStruct.Inset)
{
continue; // must be handled by the control itself
}
DrawOutsetShadow(g, dropShadowStruct, control);
}
}
// drawing the loop on an image because of speed
private void DrawOutsetShadow(Graphics g, dynamic dropShadowStruct, Control control)
{
var rOuter = control.Bounds;
var rInner = control.Bounds;
rInner.Offset(dropShadowStruct.HShadow, dropShadowStruct.VShadow);
rInner.Inflate(-dropShadowStruct.Blur, -dropShadowStruct.Blur);
rOuter.Inflate(dropShadowStruct.Spread, dropShadowStruct.Spread);
rOuter.Offset(dropShadowStruct.HShadow, dropShadowStruct.VShadow);
var originalOuter = rOuter;
var img = new Bitmap(originalOuter.Width, originalOuter.Height, g);
var g2 = Graphics.FromImage(img);
var currentBlur = 0;
do
{
var transparency = (rOuter.Height - rInner.Height)/(double) (dropShadowStruct.Blur*2 + dropShadowStruct.Spread*2);
var color = Color.FromArgb(((int)(255 * (transparency * transparency))), dropShadowStruct.Color);
var rOutput = rInner;
rOutput.Offset(-originalOuter.Left, -originalOuter.Top);
DrawRoundedRectangle(g2, rOutput, currentBlur, Pens.Transparent, color);
rInner.Inflate(1, 1);
currentBlur = (int) ((double) dropShadowStruct.Blur*(1 - (transparency*transparency)));
} while (rOuter.Contains(rInner));
g2.Flush();
g2.Dispose();
g.DrawImage(img, originalOuter);
img.Dispose();
}
private static dynamic GetDropShadowStruct(Control control)
{
if (control.Tag == null || !(control.Tag is string) || !control.Tag.ToString().StartsWith("DropShadow"))
return null;
string[] dropShadowParams = control.Tag.ToString().Split(':')[1].Split(',');
var dropShadowStruct = new
{
HShadow = Convert.ToInt32(dropShadowParams[0]),
VShadow = Convert.ToInt32(dropShadowParams[1]),
Blur = Convert.ToInt32(dropShadowParams[2]),
Spread = Convert.ToInt32(dropShadowParams[3]),
Color = ColorTranslator.FromHtml(dropShadowParams[4]),
Inset = dropShadowParams[5].ToLowerInvariant() == "inset"
};
return dropShadowStruct;
}
private void DrawRoundedRectangle(Graphics gfx, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor)
{
int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width));
bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset);
var gfxPath = new GraphicsPath();
if (cornerRadius > 0)
{
gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius,
cornerRadius, 0, 90);
gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90);
}
else
{
gfxPath.AddRectangle(bounds);
}
gfxPath.CloseAllFigures();
gfx.FillPath(new SolidBrush(fillColor), gfxPath);
if (drawPen != Pens.Transparent)
{
var pen = new Pen(drawPen.Color);
pen.EndCap = pen.StartCap = LineCap.Round;
gfx.DrawPath(pen, gfxPath);
}
}
}
}
Code is written fast without much review so there may be bugs especially if you set wring tags on controls).
PS. You may notice that inner shadow does not work for some controls. This is because they are wrappers around windows system controls. The panel cannot overcome this by itself, but you may do it like here: http://www.codeproject.com/Articles/4548/Generating-missing-Paint-event-for-TreeView-and-Li

Categories

Resources