I need to be able to rotate text in a label and align it to the left, right or center. So far I am able to do rotation with this code in the derived label's onPaint method:
float width = graphics.MeasureString(Text, this.Font).Width;
float height = graphics.MeasureString(Text, this.Font).Height;
double angle = (_rotationAngle / 180) * Math.PI;
graphics.TranslateTransform(
(ClientRectangle.Width + (float)(height * Math.Sin(angle)) - (float)(width * Math.Cos(angle))) / 2,
(ClientRectangle.Height - (float)(height * Math.Cos(angle)) - (float)(width * Math.Sin(angle))) / 2);
graphics.RotateTransform(270f);
graphics.DrawString(Text, this.Font, textBrush, new PointF(0,0), stringFormat);
graphics.ResetTransform();
And it works fine. I can see text rotated 270 degrees.
But when I try to set alignment in stringFormat it goes crazy, and I can't figure out what's going on.
How can I have text rotated by 270 degrees and align it to up?
In case somebody was looking for tips, here is the solution for 0, 90, 180, 270, and 360 degrees rotation, where StringAligment works.
One thing was choosing the right point for moving the origin to, and the second one was to modify the display rectangle according to rotation.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
SizeF txt = e.Graphics.MeasureString(Text, this.Font);
SizeF sz = e.Graphics.VisibleClipBounds.Size;
//90 degrees
e.Graphics.TranslateTransform(sz.Width, 0);
e.Graphics.RotateTransform(90);
e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Height, sz.Width), format);
e.Graphics.ResetTransform();
//180 degrees
e.Graphics.TranslateTransform(sz.Width, sz.Height);
e.Graphics.RotateTransform(180);
e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Width, sz.Height), format);
e.Graphics.ResetTransform();
//270 degrees
e.Graphics.TranslateTransform(0, sz.Height);
e.Graphics.RotateTransform(270);
e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Height, sz.Width), format);
e.Graphics.ResetTransform();
//0 = 360 degrees
e.Graphics.TranslateTransform(0, 0);
e.Graphics.RotateTransform(0);
e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Width, sz.Height), format);
e.Graphics.ResetTransform();
If you put this code in label's OnPaint event, it would display your rotated form's title four times.
Extension of Adrian Serafin's answer if you need to draw at a non-0 X,Y:
//90 degrees
e.Graphics.TranslateTransform(sz.Width, 0);
e.Graphics.RotateTransform(90);
e.Graphics.DrawString(Text, this.Font, Brushes.Black,
new RectangleF(sz.ToPointF().Y, sz.ToPointF().X, sz.Height, sz.Width), format);
e.Graphics.ResetTransform();
//180 degrees
e.Graphics.TranslateTransform(sz.Width, sz.Height);
e.Graphics.RotateTransform(180 this.Font, Brushes.Black,
new RectangleF(-sz.ToPointF().X, -sz.ToPointF().Y, sz.Width, sz.Height), format);
e.Graphics.ResetTransform();
//270 degrees
e.Graphics.TranslateTransform(0, sz.Height);
e.Graphics.RotateTransform(270);
e.Graphics.DrawString(Text, this.Font, Brushes.Black,
new RectangleF(-sz.ToPointF().Y, sz.ToPointF().X, sz.Height, sz.Width), format);
//0 = 360 degrees
e.Graphics.TranslateTransform(0, 0);
e.Graphics.RotateTransform(0);
e.Graphics.DrawString(Text, this.Font, Brushes.Black,
new RectangleF(sz.ToPointF().X, sz.ToPointF().Y, sz.Width, sz.Height), format);
e.Graphics.ResetTransform();
Related
I am trying to insert an image 800x500 inside a blank bitmap of 850x610 in the center. The inner image should be in the center and It also has a title on the top. I am attaching an image to illustrate my idea:
public static Bitmap AddBorder(Bitmap srcImage)
{
Bitmap bmp = new Bitmap(srcImage.Width + 45, srcImage.Height + 100);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(srcImage, 0, 0);
g.DrawImage(srcImage, new Rectangle(bmp.Width - 1, 0, 1, bmp.Height));
g.DrawImage(srcImage, new Rectangle(0, bmp.Height - 1, bmp.Width, 1));
return bmp;
}
I have tried to draw it using drawRectangle, drawImage etc. But, I cannot pad it properly as illustrated in the above image. I also cannot add the border to inner image.
I want to get an idea about how to do that.
The below sample sets the new bitmap size, it fills it with a background (black), draws the image in the center and finally after measuring the text will align it in the center (width check only).
public static Bitmap AddBorder(Bitmap srcImage, string text)
{
Bitmap bmp = new Bitmap(850, 610);
using(Graphics g = Graphics.FromImage(bmp))
{
// Background
g.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));
// Source Image
Rectangle rect = new Rectangle(25, 55, 800, 500);
g.DrawImage(srcImage, rect);
// Border
int borderThickness = 2;
using(Pen pen = new System.Drawing.Pen(Brushes.Black, borderThickness))
{
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawRectangle(pen, new Rectangle(rect.X - borderThickness, rect.Y - borderThickness, rect.Width + borderThickness, rect.Height + borderThickness));
}
// Text String
using (Font font = new Font("Arial", 16))
{
SizeF size = g.MeasureString(text, font);
g.DrawString(text, font, Brushes.Black, new PointF((bmp.Width / 2) - (size.Width / 2), rect.Top - (size.Height + borderThickness)));
}
}
return bmp;
}
Updated based on comments (Added also text above the centered image)!
I am currently trying to draw a gradient filled rounded rectangle onto a panel bar in a form.
From some research I found some code that allowed me to create a custom rectangle :
static class CustomRectangle
{
public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
int diameter = radius * 2;
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(bounds.Location, size);
GraphicsPath path = new GraphicsPath();
if (radius == 0)
{
path.AddRectangle(bounds);
return path;
}
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = bounds.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = bounds.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = bounds.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius)
{
if (graphics == null)
throw new ArgumentNullException("graphics");
if (brush == null)
throw new ArgumentNullException("brush");
using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
{
graphics.FillPath(brush, path);
}
}
Credit to this page
Next using this custom rectangle, I have tried using the paint method for the bar panel.
private void quickMenuBar_Paint(object sender, PaintEventArgs e)
{
LinearGradientBrush myBrush = new LinearGradientBrush(new Point(20, 20), new Point(120, 520), Color.DarkBlue, Color.RoyalBlue);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
CustomRectangle.FillRoundedRectangle(formGraphics, myBrush, new System.Drawing.Rectangle(20, 20, 100, 500), 25);
myBrush.Dispose();
formGraphics.Dispose();
}
But after executing this code, it only prints a rounded rectangle directly onto the form and behind the bar panel.
I have other methods that fill a panel with a standard rectangle using PaintEventArgs e:
e.Graphics.FillRectangle(myBrush , otherBar.ClientRectangle);
So obviously I need to use PaintEventArgs e in my custom rectangle method, but I do not know how or where to.
If there are better ways than this way of drawing a rounded rectnagles, please share.
You generally should never be using CreateGraphics(). Simply remove this line:
System.Drawing.Graphics formGraphics = this.CreateGraphics();
And use e.Graphics where you would previously use formGraphics. The Paint event is basically asking you to "paint something for me, here's the graphics object to paint on".
Since you're already providing a Graphics object instance to your rounded rectangle method, no changes are required there.
hello how to fill lineargradientbrush on the graphicspath..
i have this code and solidbrush can only fill it.. i dont know how to fill it with lineargradientbrush.. any help please..
i have this code..
class KamoteButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
int width = this.Width-1;
int height = this.Height-1;
Color gradColor_a = Color.FromArgb(162, 177, 183);
Color gradColor_b = Color.FromArgb(104, 111, 114);
int radius = this.Width / 8;
Graphics gFx = pevent.Graphics;
gFx.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath gp = new GraphicsPath();
gp.AddArc(0, 0, radius, radius, 180, 90);
gp.AddLine(width / 8, 0, width - width / 8, 0);
gp.AddArc(width - radius, 0, radius, radius, 270, 90);
gp.AddLine(width, width / 8, width, height - width / 8);
gp.AddArc(width - radius, height - radius, radius, radius, 0, 90);
gp.AddLine(width - width / 8, height, width / 8, height);
gp.AddArc(0, height - radius, radius, radius, 90, 90);
gp.AddLine(0, height - width / 8, 0, width / 8);
Rectangle r = new Rectangle(0, 0, 100, 100);
LinearGradientBrush lbg = new LinearGradientBrush(gp, gradColor_a, gradColor_b, LinearGradientMode.Vertical);
SolidBrush sb = new SolidBrush(Color.Red);
gFx.FillPath(lbg, gp);
this.Region = new Region(gp);
}
}
Your code to create the GradientBrushh won't compile:
LinearGradientBrush lbg = new LinearGradientBrush(gp,
gradColor_a, gradColor_b, LinearGradientMode.Vertical);
There is no constructor with a Path as parameter. Replace it with 2 points or 1 Rect
I am using the code below to change to shape of the winform.
It's changing the shape, but not like how I wanted.
I need the form to have curved corners.
What points should I use to get it?
public void MakeNonRectangularForm()
{
var p = new GraphicsPath();
int width = ClientSize.Width;
int height = ClientSize.Height;
p.AddClosedCurve(new Point[] { new Point(width / 2, height / 2),
new Point(width, 0), new Point(width, height / 3),
new Point(width - width / 3, height),
new Point(width / 7, height - height / 8)});
Region = new Region(p);
}
The following is some code I have used to create rounded edges before, using AddArc and lines to piece together the border:
(You can play with xRadius and yRadius to achieve your desired amount of "rounded-ness")
int xRadius = {insert value here};
int yRadius = {insert value here};
GraphicsPath edge = new GraphicsPath();
int rightHandLeft = this.Width - xRadius - 1;
int bottomSideTop = this.Height - yRadius - 1;
edge.AddArc(0, 0, xRadius, yRadius, 180, 90);
edge.AddLine(xRadius, 0, rightHandLeft, 0);
edge.AddArc(rightHandLeft, 0, xRadius, yRadius, 270, 90);
edge.AddLine(this.Width, yRadius, this.Width, bottomSideTop);
edge.AddArc(rightHandLeft, bottomSideTop, xRadius, yRadius, 0, 90);
edge.AddLine(rightHandLeft, this.Height, xRadius, this.Height);
edge.AddArc(0, bottomSideTop, xRadius, yRadius, 90, 90);
edge.AddLine(0, bottomSideTop, 0, yRadius);
this.Region = new Region(edge);
I've been trying to do this, but for some reason this is just giving me weird results:
int bpp = Screen.PrimaryScreen.BitsPerPixel;
string fontName = "Tahoma";
Font font = new Font(fontName, 10 * bpp, GraphicsUnit.Point);
Bitmap bm = new Bitmap(20 * bpp, 20 * bpp);
Graphics g = Graphics.FromImage(bm);
TextRenderer.DrawText(g, "a", font, new Rectangle(0, 0, 5 * bpp, 6 * bpp), Color.Black);
g.Flush();
pictureBox1.Image = bm;
What am I doing wrong here? I don't see anything printed on the picture. If I remove all bpp references, I can see it, but it's pretty small.
You are aware that BitsPerPixel describes the color depth (the number of memory bits that are used to describe the color of a pixel), and has nothing to do with resolution?
I assume that what you want to do is to draw the text in a size that is related to the resolution, which you can do by referring to the DpiX and DpiY properties of the Graphics object.
Update
I am not sure if yo need to bring Dpi into the calculation for this. All you need to do is to create a Rectangle that defines the desired size of your text, and then calculate the correct font size to make the text fit inside the rectangle. The following does that (but maximizes the text size both vertical and horizontal direction). It might give you some pointers to solve your problem:
Bitmap bm = new Bitmap(50, 50);
using (Font font = new Font(fontName, 10, GraphicsUnit.Point))
using (Graphics g = Graphics.FromImage(bm))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
StringFormat stringFormat = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Near
};
Rectangle rect = new Rectangle(0, 0, bm.Width, bm.Height);
// measure how large the text is on the Graphics object with the current font size
SizeF s = g.MeasureString(text, font);
// calculate how to scale the font to make the text fit
float fontScale = Math.Max(s.Width / rect.Width, s.Height / rect.Height);
using (Font fontForDrawing = new Font(font.FontFamily, font.SizeInPoints / fontScale, GraphicsUnit.Point))
{
g.DrawString(text, fontForDrawing, Brushes.Black, rect, stringFormat);
}
}
And if you want to print the text with a given point size, you don't need to go about measuring; just set the font size:
Bitmap bm = new Bitmap(20, 20);
using (Font font = new Font(fontName, 6, GraphicsUnit.Point))
using (Graphics g = Graphics.FromImage(bm))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
StringFormat stringFormat = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Near
};
Rectangle rect = new Rectangle(0, 0, bm.Width, bm.Height);
g.DrawString(text, font, Brushes.Black, rect, stringFormat);
}
I would try:
int ImgQual = 600;
int Width = 50;
int Height = 50;
Font TextFont = New Font("Tahoma", 14, FontStyle.Bold)
Bitmap bmp = New Bitmap(Width, Height);
bmp.SetResolution(ImgQual, ImgQual);
System.Drawing.Graphics g = Graphics.FromImage(bmp);
System.Drawing.StringFormat sf = New System.Drawing.StringFormat();
sf.Alignment = StringAlignment.Center;
g.DrawString("a", NumberTextFont, Brushes.Black, New RectangleF(0, 0, Width, Height), sf);
return bmp;
There are two primary reasons the "a" is small:
The height of a font is measured using a point size (which is 1/72nd of a inch, quite different from a number of pixels because different computer screens have different numbers of pixels per inch).
Font height is measured from the top of a line of text to the bottom. As some letters have ascenders (the tall bar in "h") and others have descenders (the dangly bit of a "g"), an "a" will occupy only about a third of the height of the font.
If you wish your "a" to fill the image, then you will need to draw it into a larger rectangle and "clip off" the empty regions above and below the "a". If you're not too worried about screen DPI on different computers, then you can just experiment until you find a font size (and position to draw at) that works.