Arc graphic quality - c#

Back here. Is there any way to improve the quality of the Arc?
I'm using e.Graphics.SmoothingMode = SmoothingMode.AntiAlias
This is the piece of code that creates the arc:
using (GraphicsPath gp = new GraphicsPath())
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
gp.Reset();
gp.AddPie(_OuterRectangle, (float)_Properties.Origin, (float)_Properties.GaugeType);
gp.Reverse();
gp.AddPie(_InnerRectangle, (float)_Properties.Origin, (float)_Properties.GaugeType);
gp.Reverse();
pArea.SetClip(gp);
using (Pen oPen = new Pen(this.ForeColor, 2f))
{
e.Graphics.DrawPath(oPen, gp);
}
e.Graphics.SetClip(ClientRectangle);
}
Thanks in advance.
EDIT:
I've did what LarsTech proposed and now the quality is perfect, but I'm not having the figure I need:
OuterRectangle: is the ClientRectangle area, that I'm manipulating it to make Width and Height the same lenght;
InnerRectangle: is 2/3ths of the ClientRectangle area, ergo, of the OuterRectangle;
Properties.Origin: is the angle where the arc starts. I have it in an enumerator as Cardinal Points, where North is 270, East is 0,
and so. In case of the figure, is SouthWest, 135 degrees;
Properties.GaugeType: is another enumerator that says if is Complete = 360, Half = 180, Quarter = 90, so with that I can determine the sweep angle. In case of the figure is ThreeQuarter, 270 degrees.

The problem:
When clipping a region of the current Graphics (Graphics.SetClip method), the resulting drawing loses quality, because the antialiasing effect generated by Graphics.SmoothingMode = SmoothingMode.AntiAlias is lost.
A possible solution is to avoid clipping the region defined by the GraphicsPath used to design the arcs (GraphicsPath.AddPie method); this, however, leaves the lines of the Pie visible, compromising the shape.
Another solution is to draw an ellipsis in the center of the arcs using the background color of the Canvas. Since the arcs are drawn using two rectangles, we can use the inner rectagle, inflate it (Rectangle.Inflate method) as needed (a fraction - Pen.Width / 2 - of the Pen size used for the ouline, usually).
This allows to delete the artifacts generated by the GraphicsPath shapes and to draw some other graphics content in the center of the shapes.
For example, using different Brushes:
LinearGradientBrush HatchBrush TextureBrush
Of course there are other methods to achieve the same result. We could draw the Arcs using the GraphicsPath.AddArc method, extract or calculate the first and last points of the Arcs and use them to draw two lines (GraphicsPath.AddLine) that will close the figures.
But, since we want to draw different graphics objects in the center of the arcs, these objects will cover the center area anyway.
How to use this code:
In a Form, add a TrackBar (named tbarSpeed, here)
Add a PictureBox (named Canvas), with Size (200, 200).
Wire up the TrackBar tbarSpeed_Scroll event and the Panel Canvas_Paint event.
using System.Drawing;
using System.Drawing.Drawing2D;
float GaugeValue = 88.0f;
float GaugeSweepAngle = 270.0f;
float GaugeStartAngle = 135.0F;
private void Canvas_Paint(object sender, PaintEventArgs e)
{
var canvas = sender as Control;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
var outerRectangle = new Rectangle(10, 10, 180, 180);
var innerRectangle = new Rectangle(30, 30, 140, 140);
var blendRectangle = new Rectangle(10, 10, 180, 160);
var innerCenter = new PointF(outerRectangle.Left + (outerRectangle.Width / 2),
outerRectangle.Top + (outerRectangle.Height / 2));
float gaugeLength = (outerRectangle.Width / 2) - 2;
using (var path = new GraphicsPath())
{
path.AddPie(outerRectangle, GaugeStartAngle, GaugeSweepAngle);
path.AddPie(innerRectangle, GaugeStartAngle, GaugeSweepAngle);
innerRectangle.Inflate(-1, -1);
using (var pen = new Pen(Color.White, 3f))
using (var backgroundbrush = new SolidBrush(canvas.BackColor))
using (var gradientBrush = new LinearGradientBrush(blendRectangle,
Color.Green, Color.Red, LinearGradientMode.ForwardDiagonal))
{
var blend = new Blend()
{
Factors = new[] { 0.0f, 0.0f, 0.1f, 0.3f, 0.7f, 1.0f },
Positions = new[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }
};
gradientBrush.Blend = blend;
e.Graphics.FillPath(gradientBrush, path);
e.Graphics.DrawPath(pen, path);
e.Graphics.FillEllipse(backgroundbrush, innerRectangle);
using (var format = new StringFormat())
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
innerRectangle.Location = new Point(innerRectangle.X, innerRectangle.Y + canvas.Font.Height);
e.Graphics.DrawString(GaugeValue.ToString() + "%", canvas.Font, Brushes.White, innerRectangle, format);
}
using (var mx = new Matrix())
{
mx.RotateAt(GaugeStartAngle + 90 + (GaugeValue * (GaugeSweepAngle / 100)), innerCenter);
e.Graphics.Transform = mx;
e.Graphics.DrawLine(pen, innerCenter, new PointF(innerCenter.X, innerCenter.Y - gaugeLength));
e.Graphics.ResetTransform();
}
}
}
}
private void tbarSpeed_Scroll(object sender, EventArgs e)
{
GaugeValue = tbarSpeed.Value;
Canvas.Invalidate();
}
Sample code on PasteBin

Related

How can I fill the circular sector of an elliptic shape with a color gradient?

What I want to do is to create this rotating cone visual effect.
I had previously used DirectX for that.
What i have tried so far:
Even if I'm changing the thickness to 50 or more, the Arc is still not filled.
public partial class Form1 : Form
{
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var center = new Point(pictureBox1.Width / 2, pictureBox1.Height / 2);
var innerR = 30;
var thickness = 20;
var startAngle = 0;
var arcLength = 360;
var outerR = innerR + thickness;
var outerRect = new Rectangle
(center.X - outerR, center.Y - outerR, 2 * outerR, 2 * outerR);
var innerRect = new Rectangle
(center.X - innerR, center.Y - innerR, 2 * innerR, 2 * innerR);
using (var p = new GraphicsPath())
{
p.AddArc(outerRect, startAngle, arcLength);
p.AddArc(innerRect, startAngle + arcLength, -arcLength);
p.CloseFigure();
e.Graphics.FillPath(Brushes.Green, p);
e.Graphics.DrawPath(Pens.Green, p);
}
}
}
I want to be able to fill the arc even when the thickness is 20 or less.
Or when the value of the innerR radius changes.
The goal is to be able to fill the arc in any case.
Here's one method of drawing that cone.
It looks like a Radar sweep, so you may want to define the sweep angle and the rotation speed (how much the current rotation angle is increased based on the Timer's interval).
Using a standard System.Windows.Forms.Timer to invalidate the Canvas that contains the Image you're showing here.
The Radar contour (the external perimeter) is centered on the canvas and drawn in relation to the thickness specified (so it's always sized as the canvas bounds). It doesn't necessarily be a perfect circle, it can be elliptical (as in the image here)
The Cone section is drawn adding an Arc to a GraphicsPath and is closed drawing two lines, from the center point of the outer GraphicsPath to the starting and ending points of the Arc (I think this is a simple method to generate a curved conic figure, it can be used in different situations and lets you generate different shapes almost without calculations, see the code about this)
It's filled with a LinearGradientBrush, the section near the center has less transparency than the section near the border; adjust as required
Each time the rotation angle reaches 360°, it's reset to 0.
This is delegated to the Timer's Tick event handler
=> Built with .Net 7, but if you need to adapt it to .Net Framework, the only things to change are the syntax of the using blocks, remove the null-forgiving operator from here: canvas!.ClientRectangle and nullable reference types (e.g., change object? to just object)
public partial class SomeForm : Form {
public SomeForm() {
InitializeComponent();
radarTimer.Interval = 100;
radarTimer.Tick += RadarTimer_Tick;
}
float coneSweepAngle = 36.0f;
float coneRotationAngle = .0f;
float radarSpeed = 1.8f;
float radarThickness = 5.0f;
System.Windows.Forms.Timer radarTimer = new System.Windows.Forms.Timer();
private void RadarTimer_Tick(object? sender, EventArgs e) {
coneRotationAngle += radarSpeed;
coneRotationAngle %= 360.0f;
canvas.Invalidate();
}
private void canvas_Paint(object sender, PaintEventArgs e) {
var center = new PointF(canvas.Width / 2.0f, canvas.Height / 2.0f);
RectangleF outerRect = canvas!.ClientRectangle;
outerRect.Inflate(-(radarThickness / 2.0f), -(radarThickness / 2.0f));
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var pathOuter = new GraphicsPath();
using var pathInner = new GraphicsPath();
pathOuter.AddEllipse(outerRect);
pathInner.StartFigure();
pathInner.AddArc(outerRect, coneRotationAngle, coneSweepAngle);
var arcPoints = pathInner.PathPoints;
PointF first = arcPoints[0];
PointF last = arcPoints[arcPoints.Length - 1];
pathInner.AddLines(new[] { center, last, center, first });
pathInner.CloseFigure();
using var outerPen = new Pen(Color.FromArgb(100, Color.Red), radarThickness);
using var innerBrush = new LinearGradientBrush(
center, first, Color.FromArgb(200, Color.Orange), Color.FromArgb(20, Color.Orange));
e.Graphics.FillPath(innerBrush, pathInner);
e.Graphics.DrawPath(outerPen, pathOuter);
}
}
This is how it works:

How to fill text with 2 different color/texture

I draw text on top of a image using Path.Addstring and filling it with a color and it works perfectly. Now I would like to split(bisect) the text vertically and have 2 different colors or textures. For eg. the top half of the text with a solid brush and the bottom half with hatch brush. I'd like to know if this is possible and which way should I implement it.
Reference image created using paint.net software. I drew a line to split the text and filled the bottom part with a different texture.
*I don't want the line to be visible in the final output.
Possible.
Fill the path with the solid brush.
Get the rectangle that bounds the path through the GraphicsPath.GetBounds method.
Call the Graphics.SetClip method to exclude the top half of the rectangle.
Fill the path with a TextureBrush or HatchBrush.
An example that uses a HatchBrush to fill the second vertical half of the path.
private void SomeControl_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
var r = (sender as Control).ClientRectangle;
using (var gp = new GraphicsPath())
using (var sf = new StringFormat())
using (var fnt = new Font("Blackoak Std", 72))
using (var hbr = new HatchBrush(HatchStyle.Percent25, Color.White, Color.Red))
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
gp.AddString("RED", fnt.FontFamily, (int)fnt.Style, GetEmFontSize(fnt), r, sf);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillPath(Brushes.Red, gp);
var rf = gp.GetBounds();
rf.Height /= 2f;
g.SetClip(rf, CombineMode.Exclude);
g.FillPath(hbr, gp);
g.ResetClip();
g.SmoothingMode = SmoothingMode.None;
}
}
private float GetEmFontSize(Font fnt) =>
fnt.SizeInPoints * (fnt.FontFamily.GetCellAscent(fnt.Style) +
fnt.FontFamily.GetCellDescent(fnt.Style)) / fnt.FontFamily.GetEmHeight(fnt.Style);
See also the other HatchStyle values.

How to get XY of pictureBox1 after it has been transformed

I have a list of Points that have been drawn on pictureBox1.
pictureBox1 has been transformed.
Now, I want to get XY coordinates of the point that was drawn as I hover over any drawn point.
When I hover over the pictureBox1, I am getting the XY of the pictureBox -- not a transformed XY.
Can you help me get to the transformed XY?
Thanks
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
int height = pictureBox1.ClientSize.Height / 2;
int width = pictureBox1.ClientSize.Width / 2;
//=====
//scale
//=====
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TranslateTransform(-width, -height);
e.Graphics.ScaleTransform(2f, 2f);
//===========
//draw center
//===========
e.Graphics.DrawLine(new Pen(Color.Black, 0.5f), new Point(width - 2, height), new Point(width + 2, height));
e.Graphics.DrawLine(new Pen(Color.Black, 0.5f), new Point(width, height - 2), new Point(width, height + 2));
//===========
//draw points
//===========
foreach (var p in Points)
{
Point[] pts = new Point[] { new Point(p.X, p.Y) };
Rectangle rc = new Rectangle(pts[0], new Size(1, 1));
e.Graphics.DrawRectangle(Pens.Red, rc);
}
}
As a variation to #Vitaly's answer you can do this:
After transforming the Graphics object you can save its transformation matrix e.Graphics.Transform in a variable:
Matrix matrix = null;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
int height = pictureBox1.ClientSize.Height / 2;
int width = pictureBox1.ClientSize.Width / 2;
//=====
//scale
//=====
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TranslateTransform(-width, -height);
e.Graphics.ScaleTransform(2f, 2f);
matrix = e.Graphics.Transform; // save the transformation matrix!
...
This is necessary as the transfomation data are lost after the Paint event!
Note that the GraphicsState graphics.Save()&Restore() functions can't be used very well for this purpose, as it only puts the state on the stack for using it once, meaning it doesn't save these data in a persistent way.
Later you can use the Matrix and this function to either transform Points with the same matrix or reverse the transformation, e.g. for mouse coordinates:
PointF transformed(Point p0, bool forward)
{
Matrix m = matrix.Clone();
if (!forward) m.Invert();
var pt = new Point[] { p0 };
m.TransformPoints(pt);
return pt[0];
}
Now my MouseMove event shows the location both raw and re-transformed:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = e.Location + " <-> " + transformed(e.Location, false) ;
}
And to test the forward transformation you could add this to the end of the Paint event:
e.Graphics.ResetTransform();
for (int i = 0; i < Points.Count; i++)
{
Point[] pts = new Point[] { Point.Round(transformed(Points[i], true)) };
Rectangle rc = new Rectangle(pts[0], new Size(19, 19));
e.Graphics.DrawRectangle(Pens.Red, rc);
}
This first clears all the transformations and then paints larger Rectangles at the same locations by calling the transformed function.
Note that this will also work with a rotated Graphics object. (Although the last test does not draw the larger rectangles rotated, just moved to the right locations.)
Also note that I return PointF for better precision when scaling with fractions. You can use Point.Round (or Point.Truncate) to get Point.
Do have a look the the Matrix.Elements: They contain the numbers you have used:
float scaleX = matrix.Elements[0];
float scaleY = matrix.Elements[3];
float transX = matrix.Elements[4];
float transY = matrix.Elements[5];
Finally: It is well worth studying the many methods of Matrix..!
You can create a Matrix with necessary transformations and apply it in pictureBox1_Paint(...) via MultiplyTransform(...):
https://msdn.microsoft.com/en-us/library/bt34tx5d(v=vs.110).aspx
Then you can use Matrix::TransformPoints(...) to get transformed XY

RotateTransform slowing the FillRectangle function in C# GDI+?

I have a function that draw points on the screen. This function worked very well until I added the line with panelGraphics.RotateTransform. When this line is there, the process of doing one repaint is very long. My list of points contains about 5000 points and without the rotation, it's done in a couple of milliseconds but with that line it could take up to 500 ms which is VERY slow. Do you have any idea why RotateTransform is so slow and also, what can I do to optimize this?
private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
Graphics panelGraphics = panel1.CreateGraphics();
panelGraphics.TranslateTransform((panel1.Width / 2) + _panW, (panel1.Height / 2) + _panH);
//Problematic line...
panelGraphics.RotateTransform(230 - Convert.ToInt32(_dPan), System.Drawing.Drawing2D.MatrixOrder.Prepend);
PointF ptPrevious = new PointF(float.MaxValue, float.MaxValue);
foreach (PointF pt in _listPoint)
{
panelGraphics.FillRectangle(myBrush, (pt.X / 25) * _fZoomFactor, (pt.Y / 25) * _fZoomFactor, 2, 2);
}
myBrush.Dispose();
myPen.Dispose();
panelGraphics.Dispose();
}
The reason is that each rectangle has to be rotated. Rotation can be a slow operation, especially for none square angles.
The better approach in this case is to first create a "hidden" bitmap which you draw the rectangles into. Then apply the rotation to your main graphics object and draw the hidden bitmap onto your main bitmap (control). Something like this -
private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
Graphics panelGraphics = e.Graphics; //use the provided Graphics object
// create an internal bitmap to draw rectangles to
Bitmap bmp = new Bitmap(this.ClientSize.Width, _
this.ClientSize.Height, _
Imaging.PixelFormat.Format32bppPArgb);
using (Graphics g = Graphics.FromImage(bmp)) {
PointF ptPrevious = new PointF(float.MaxValue, float.MaxValue);
foreach (PointF pt in _listPoint) {
g.FillRectangle(myBrush, (pt.X / 25) * _fZoomFactor, _
(pt.Y / 25) * _fZoomFactor, 2, 2);
}
}
panelGraphics.TranslateTransform((panel1.ClientSize.Width / 2) + _panW, _
(panel1.ClientSize.Height / 2) + _panH);
//Problematic line...
panelGraphics.RotateTransform(230 - Convert.ToInt32(_dPan), _
System.Drawing.Drawing2D.MatrixOrder.Prepend);
panelGraphics.DrawImage(bmp, 0, 0); //adjust x/y as needed
bmp.Dispose;
myBrush.Dispose();
myPen.Dispose();
}

C# GDI+ curve drawing issue

I'm trying to draw a series of connected segments, but the curved segments seem to produce an artifact, whereby the outer side of the curve is not smooth at all, but very jagged. This is part of a GIS program I am making.
For these lines, the line itself needs to be quite wide, as this represents the range of data that can be collected on this line for the GIS data. There also has to be an area directly under the line where no data is collected. This also can be wide, but not as wide as the main line.
I have done this using a graphics path, which I then widen and use as a clipping region to block the area directly under the line. I then draw the actual line. The sample code below does this, with made up values for ease of regenerating.
This works fine with straight lines, but with curved lines there are very irregular shapes on the outside of the curves. I have no idea why this happens.
Any ideas would be much appreciated, cheers,
Greg
I made this sample code using a basic form with a picturebox and a button on it, whereby when I clicked the button it would execute this method:
private void drawCurvedLine()
{
//initialise the plot area:
Bitmap image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.BackgroundImage = image;
Graphics g = Graphics.FromImage(image);
//the width of the pen represents the width of a sonar swathe:
Pen widePen = new Pen(new SolidBrush(Color.FromArgb(80, Color.Blue)), 50);
PointF[] points = new PointF[4];
//first straight:
points[0] = new PointF(287.284149F,21.236269F);
points[1] = new PointF(183.638443F,406.936249F);
//second straight:
points[2] = new PointF(130.842773F, 515.574036F);
points[3] = new PointF(-1950.91321F, 3491.868F);
//graphics path for the line:
GraphicsPath gPath = new GraphicsPath();
gPath.AddLine(points[0], points[1]);
gPath.AddArc(new RectangleF(-445.464447F,3.84924316F,640.067444F,640.067444F), -(90 - 105.0412369999982F), 10.8775282F);
gPath.AddArc(new RectangleF(-445.464417F, 3.84915161F, 640.067444F, 640.067444F), -(90 - 115.91811484539707F), 10.8775091F);
gPath.AddLine(points[2], points[3]);
//widen the line to the width equal to what the fish will not be able to see:
gPath.Widen(new Pen(Color.White, 10));
//now exclude that widened line from the main graphics:
g.ExcludeClip(new Region(gPath));
//draw the swathe line:
g.DrawPath(widePen, gPath);
//reset the clipping for the next line:
g.ResetClip();
}
Try to use a separate GraphicsPath for excluded region:
private void drawCurvedLine()
{
//initialise the plot area:
Bitmap image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.BackgroundImage = image;
using(Graphics g = Graphics.FromImage(image))
{
PointF[] points = new PointF[4];
//first straight:
points[0] = new PointF(287.284149F, 21.236269F);
points[1] = new PointF(183.638443F, 406.936249F);
//second straight:
points[2] = new PointF(130.842773F, 515.574036F);
points[3] = new PointF(-1950.91321F, 3491.868F);
//graphics path for the line:
using(GraphicsPath gPath = new GraphicsPath())
{
gPath.AddLine(points[0], points[1]);
gPath.AddArc(new RectangleF(-445.464447F, 3.84924316F, 640.067444F, 640.067444F), -(90 - 105.0412369999982F), 10.8775282F);
gPath.AddArc(new RectangleF(-445.464417F, 3.84915161F, 640.067444F, 640.067444F), -(90 - 115.91811484539707F), 10.8775091F);
gPath.AddLine(points[2], points[3]);
//widen the line to the width equal to what the fish will not be able to see:
using(GraphicsPath innerPath = (GraphicsPath)gPath.Clone())
{
using(Pen pen = new Pen(Color.White, 10))
{
innerPath.Widen(pen);
}
//now exclude that widened line from the main graphics:
using(Region reg = new Region(innerPath))
{
g.ExcludeClip(reg);
//draw the swathe line:
//the width of the pen represents the width of a sonar swathe:
using(Pen widePen = new Pen(new SolidBrush(Color.FromArgb(80, Color.Blue)), 50))
{
g.DrawPath(widePen, gPath);
}
//reset the clipping for the next line:
g.ResetClip();
}
}
}
}
}
Set the smoothing mode properly on your Graphics instance. Take a look here.
Try setting the CompositingQuality, the InterpolationMode and the SmoothingMode properties to increase the quality of your Graphics object:
using(Graphics g = Graphics.FromImage(image))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.AntiAlias;
//...
}

Categories