Reputation: 206
I want to have a custom CheckBox in C# that has a gradiant backgronud on it. I overrided OnPaint(PaintEventArgs e) as below:
Graphics g = e.Graphics;
base.OnPaint(e);
//// Fill the background
//SetControlSizes();
// Paint the outer rounded rectangle
g.SmoothingMode = SmoothingMode.AntiAlias;
using (GraphicsPath outerPath = GeneralUtilities.RoundedRectangle(mLabelRect, 1, 0))
{
using (LinearGradientBrush outerBrush = new LinearGradientBrush(mLabelRect,
mGradientTop, mGradientBottom, LinearGradientMode.Vertical))
{
g.FillPath(outerBrush, outerPath);
}
using (Pen outlinePen = new Pen(mGradientTop, mRectOutlineWidth))
{
outlinePen.Alignment = PenAlignment.Inset;
g.DrawPath(outlinePen, outerPath);
}
}
//// Paint the gel highlight
using (GraphicsPath innerPath = GeneralUtilities.RoundedRectangle(mHighlightRect, mRectCornerRadius, mHighlightRectOffset))
{
using (LinearGradientBrush innerBrush = new LinearGradientBrush(mHighlightRect,
Color.FromArgb(mHighlightAlphaTop, Color.White),
Color.FromArgb(mHighlightAlphaBottom, Color.White), LinearGradientMode.Vertical))
{
g.FillPath(innerBrush, innerPath);
}
}
// Paint the text
TextRenderer.DrawText(g, Text, Font, mLabelRect, Color.White, Color.Transparent,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
It works and make a gradiant for background, but checkbox disappear under the gradiant and can't access. Now, what shall I do ??? please help me as soon as possible
Upvotes: 1
Views: 4203
Reputation: 12420
EDIT:
OK I know what's wrong. The checkbox draws an underlaying background automatically that covers anything previously drawn.
In this case, you must draw the appearance of the checkbox (i.e. the checked state, etc.) by yourself.
You should override the OnPaintBackground
function for drawing the background, instead of OnPaint
.
Another option is to call base.OnPaint(e)
after you've drawn the background.
The checkbox doesn't "disappear" under the gradient and you can still access it. You just drawn the "background" above the "foreground".
The base control draw the appearance of the checkbox in the base.OnPaint(e)
function. If you draw anything after calling it, those things will be drawn as an "overlay" in front of the drawn checkbox, that's why you can't see the appearance of the checkbox.
If you are going to draw the Text by yourself also, you would not want the internally-drawn checkbox text to appear. In this case you will need to draw the appearance of the checkbox by yourself also.
As I already mentioned, if you are only going to draw a custom background, use OnPaintBackground
instead.
Upvotes: 1