c# drawing text over an object - c#

i am drawing a dashed line over an object using this method:
// Get Graphics object from chart
Graphics graph = e.ChartGraphics.Graphics;
PointF point1 = PointF.Empty;
PointF point2 = PointF.Empty;
// Set Maximum and minimum points
point1.X = -110;
point1.Y = -110;
point2.X = 122;
point2.Y = 122;
// Convert relative coordinates to absolute coordinates.
point1 = e.ChartGraphics.GetAbsolutePoint(point1);
point2 = e.ChartGraphics.GetAbsolutePoint(point2);
// Draw (dashed) connection line
float[] dashValues = { 4, 2 };
Pen dashPen= new Pen(Color.Yellow, 3);
dashPen.DashPattern = dashValues;
graph.DrawLine(dashPen, point1, point2);
and i would like to know whether it is possible to write text over an object the same way/.??

You should look at the DrawString method.

Yes you can accomplish this in Graphics.DrawString

Related

how to draw polygon including negative points ? in C#

i am doing c# project. i have found a problem and unable to find answer of this problem that's why i am posting here/
i am implementing procedural floor plan generation in c#. at first i need to draw a polygon to on given points to generate grid. points can be positive or negative. points will be in floating.
From the Microsoft Documentation i am able to draw polygon for the floating positive points, but when i change points to negative it does not draw anything on form.
this method id drawing x,y coordinates 0,0 in the corner .
code example
public void DrawPolygonPointF(PaintEventArgs e)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create points that define polygon.
PointF point1 = new PointF(50.0F, 50.0F);
PointF point2 = new PointF(100.0F, 25.0F);
PointF point3 = new PointF(200.0F, 5.0F);
PointF point4 = new PointF(250.0F, 50.0F);
PointF point5 = new PointF(300.0F, 100.0F);
PointF point6 = new PointF(350.0F, 200.0F);
PointF point7 = new PointF(250.0F, 250.0F);
PointF[] curvePoints =
{
point1,
point2,
point3,
point4,
point5,
point6,
point7
};
// Draw polygon curve to screen.
e.Graphics.DrawPolygon(blackPen, curvePoints);
}
i have negative coordinates value for example pointF(300,-250) this method is not drawing nothing for negative coordinates value.
So please give me brief solution because i don't know much about drawing.
Thank you
In C# 0,0 is the top left corner of the screen. So negative values are off the left or top edge of your form. You need to transform your coordinates from your coordinate space to the form's. To place 0,0 dead center, you would do this:
int screenX = myX + windowWidth / 2;
int screenY = myY + windowHeight / 2;
Building off of the answer #pquest gave, and your newly added sample code, doing a "real" GDI transformation would look like this:
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create points that define polygon.
PointF point1 = new PointF(50.0F, 50.0F);
PointF point2 = new PointF(100.0F, 25.0F);
PointF point3 = new PointF(200.0F, 5.0F);
<...snip...>
//Apply a translation Transformation to move 0,0 to the center of the
//window. You can now draw your points with negative values, without doing
//any addition to them.
int screenX = windowWidth / 2;
int screenY = windowHeight / 2;
e.Graphics.TranslateTransform((float) screenX, (float) screenY);
// Draw polygon curve to screen.
e.Graphics.DrawPolygon(blackPen, curvePoints);
GDI Transformations are very powerful. You can use them to move points around, flip points horizontally or vertically, scale things bigger or smaller, distort like a parallelogram, and even do rotations. All of these can be combined in to what is called a transformation matrix to get some very cool results.
More examples can be found on MSDN.
That's working for me to this problem.
you just need to add couple lines of code in your code.
int windowWidth = this.ClientSize.Width;
int windowHeight = this.ClientSize.Height;
int screenX = windowWidth / 2;
int screenY = windowHeight / 2;
e.Graphics.TranslateTransform((float)screenX, (float)screenY);

using graphic to draw pentagon

Currently i'm trying to draw a pentagon with graphic but to no avil as i'm unable to get the points. So far I had tried it to draw out a triangle which I had succeeded , code is as below;
SolidBrush sb = new SolidBrush(painting);
PointF point1 = new PointF(25, 350);
PointF point2 = new PointF(450, 350);
PointF point3 = new PointF(225, 50);
PointF[] curvePoints = { point1, point2, point3 };
g.FillPolygon(sb, curvePoints);
paintstart = false;
(using triangle value as base)i thought of adding two more points (since pentagon have 5 sides) and my code for pentagon goes like this
SolidBrush sb = new SolidBrush(painting);
PointF point1 = new PointF(25, 350);
PointF point2 = new PointF(450, 350);
PointF point3 = new PointF(225, 50);
PointF point4 = new PointF(10, 150);
PointF point5 = new Point(475, 150);
PointF[] curvePoints = { point1, point2, point3, point4,point5};
g.FillPolygon(sb, curvePoints);
paintstart = false;
after added the 5th point, the whole shape figure goes distorted while 4th point remain alright.
Any idea why after adding the 5th point, the whole shape goes distorted? I add + 15 value to the x value of the pentagon base(450)and y axis remained the same.
Any help is appreciated thanks !
The order of the points matters when you have more than three points:
PointF[] curvePoints = { point1, point2, point5, point3, point4 };

Drawing a polygon according to the input coordinates

How can i draw a polygon according to the input coordinates which are given in C#.
You didn't show any code because based on those coordinate, you are applying some form of scaling to the image.
Using the Paint event of a PictureBox, here is an example using those coordinates on the screen. It fills in the polygon, then draws the border, then it loops through all the points to draw the red circle:
void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.Clear(Color.White);
// draw the shading background:
List<Point> shadePoints = new List<Point>();
shadePoints.Add(new Point(0, pictureBox1.ClientSize.Height));
shadePoints.Add(new Point(pictureBox1.ClientSize.Width, 0));
shadePoints.Add(new Point(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height));
e.Graphics.FillPolygon(Brushes.LightGray, shadePoints.ToArray());
// scale the drawing larger:
using (Matrix m = new Matrix()) {
m.Scale(4, 4);
e.Graphics.Transform = m;
List<Point> polyPoints = new List<Point>();
polyPoints.Add(new Point(10, 10));
polyPoints.Add(new Point(12, 35));
polyPoints.Add(new Point(22, 35));
polyPoints.Add(new Point(24, 22));
// use a semi-transparent background brush:
using (SolidBrush br = new SolidBrush(Color.FromArgb(100, Color.Yellow))) {
e.Graphics.FillPolygon(br, polyPoints.ToArray());
}
e.Graphics.DrawPolygon(Pens.DarkBlue, polyPoints.ToArray());
foreach (Point p in polyPoints) {
e.Graphics.FillEllipse(Brushes.Red,
new Rectangle(p.X - 2, p.Y - 2, 4, 4));
}
}
}
You may use Graphics.DrawPolygon. You can store the coordinates in an array of Point and then you can pass that to DrawPolygon method. You may wanna see:
Drawing with Graphics in WinForms using C#
private System.Drawing.Graphics g;
System.Drawing.Point[] p = new System.Drawing.Point[6];
p[0].X = 0;
p[0].Y = 0;
p[1].X = 53;
p[1].Y = 111;
p[2].X = 114;
p[2].Y = 86;
p[3].X = 34;
p[3].Y = 34;
p[4].X = 165;
p[4].Y = 7;
g = PictureBox1.CreateGraphics();
g.DrawPolygon(pen1, p);
This simple function is able to generate an array of PointF equal to the vertices of the regular polygon to be drawn, where "center" is the center of the polygon, "sides" is its number of sides, "sideLength" is the size of each side in pixels and "offset" is its slope.
public PointF[] GetRegularPolygonScreenVertex(Point center, int sides, int sideLength, float offset)
{
var points = new PointF[sides];
for (int i = 0; i < sides; i++)
{
points[i] = new PointF(
(float)(center.X + sideLength * Math.Cos((i * 360 / sides + offset) * Math.PI / 180f)),
(float)(center.Y + sideLength * Math.Sin((i * 360 / sides + offset) * Math.PI / 180f))
);
}
return points;
}
The result obtained can be used to draw a polygon, e.g. with the function:
GraphicsObject.DrawPolygon(new Pen(Brushes.Black, GetRegularPolygonScreenVertex(new Point(X, Y), 6, 30, 60f));
Which will generate a regular hexagon with a side of 30 pixels inclined by 30°.
hex

Filling Color in a hexagon in WPF

I'm having problem in filling the hexagon using this code, when this code runs it draws only the outline of the hexagon that is "White", I want to fill the hexagon with a color but it is not working.
I have searched a lot and tried many things like drawingContext.Drawing() , drawingBrush, etc.
Am I missing something in this code? This is the code:
public void DrawHexagon(DrawingContext drawingContext)
{
GeometryGroup hexaKey = new GeometryGroup();
//making lines for hexagon
hexaKey.Children.Add(
new LineGeometry(new Point(X1, Y1), new Point(X2, Y2)));
hexaKey.Children.Add(
new LineGeometry(new Point(X2, Y2), new Point(X3, Y3)));
hexaKey.Children.Add(
new LineGeometry(new Point(X3, Y3), new Point(X4, Y4)));
hexaKey.Children.Add(
new LineGeometry(new Point(X4, Y4), new Point(X5, Y5)));
hexaKey.Children.Add(
new LineGeometry(new Point(X5, Y5), new Point(X6, Y6)));
hexaKey.Children.Add(
new LineGeometry(new Point(X6, Y6), new Point(X1, Y1)));
//
// Create a GeometryDrawing.
//
GeometryDrawing hexaKeyDrawing = new GeometryDrawing();
hexaKeyDrawing.Geometry = hexaKey;
// Paint the drawing with a gradient.
hexaKeyDrawing.Brush =new SolidColorBrush(Colors.Red);
// Outline the drawing with a solid color.
hexaKeyDrawing.Pen = new Pen(Brushes.White, 2);
drawingContext.DrawGeometry(hexaKeyDrawing.Brush, hexaKeyDrawing.Pen, hexaKeyDrawing.Geometry);
}
LineGeometry doesn't have a way to fill... they're just lines. You need a path. The MSDN has an example
An example, how to fill hexagons: http://www.codeproject.com/Articles/14948/Hexagonal-grid-for-games-and-other-projects-Part-1
In your example you have a number of LineGeometry instances inside a GeometryGroup inside a GeometryDrawing.
First, I'd link to bring to your attention that you're not actually using the GeometryDrawing. In your example you've used it solely as a place holder for your GemetryGroup.
Ignoring this the problem is that LineGeometry instances were not intended to draw shapes and GeometryGroup is not able to realize that your 6 LineSegments together form a closed shape.
Despair not however as there is a way to accomplish what you want: PathGeometry. This geometry essentially defines the contour of a region that may be filled! This contour may is defined by a starting point and a series of PathSegments.
private Point GetExtremity(Point center, double radius, double orientation)
{
return new Point(
center.X + Math.Cos(orientation) * radius,
center.Y + Math.Sin(orientation) * radius
);
}
public void DrawUniformShape(DrawingContext context, Brush brush, Pen pen, Point center, double radius, int sides, double orientationRadians)
{
context.DrawGeometry(
brush,
pen,
new PathGeometry(
Enumerable.Repeat(
new PathFigure(
GetExtremity(center, radius, orientationRadians),
from vertex in Enumerable.Range(1, sides - 1)
let angle = orientationRadians + vertex * 2 * Math.PI / sides
select new LineSegment(GetExtremity(center, radius, angle), true),
true
),
1
)
)
);
}
public void DrawBarnColouredHexagon(DrawingContext context, Point center, double radius, double orientation)
{
DrawUniformShape(
context,
Brushes.Red,
new Pen(Brushes.White, 2),
center,
radius,
6,
0
);
}

c# can you get position from axis without having a form?

I have a WinForm application that I would like to convert to a service. It has two mscharts on it. I don't need to see those charts anymore because the application creates bitmaps out of them. I am drawing a line on one chart depending on data from another chart, like this:
// Get Graphics object from chart
Graphics graph = e.ChartGraphics.Graphics;
// Convert X and Y values to screen position
float pixelYMax = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.Y, CreatininePoint.YValues[0]);
float pixelXMax = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.X, CreatininePoint.XValue);
float pixelYMin = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.Y, CreatininePoint.YValues[0]-20);
float pixelXMin = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.X, CreatininePoint.XValue);
PointF point1 = PointF.Empty;
PointF point2 = PointF.Empty;
// Set Maximum and minimum points
point1.X = pixelXMax;
point1.Y = pixelYMax-10;
point2.X = pixelXMin;
point2.Y = 84;
// Convert relative coordinates to absolute coordinates.
point1 = e.ChartGraphics.GetAbsolutePoint(point1);
point2 = e.ChartGraphics.GetAbsolutePoint(point2);
float[] dashValues = { 4,2 };
Pen blackPen = new Pen(Color.Black, 1);
blackPen.DashPattern = dashValues;
//e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5));
//graph.DrawLine(blackPen, point1, point2);
// Draw connection line
graph.DrawLine(new Pen(Color.Black, 2), point2, point1);
// Create string to draw.
//String drawString = creatininept + " ng/mL";
String drawString = "67 ng/mL";
// Create font and brush.
Font drawFont = new Font("Arial", 7);
SolidBrush drawBrush = new SolidBrush(Color.Black);
// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(point1.X,point1.Y+5);
// Draw string to screen.
graph.DrawString(drawString, drawFont, drawBrush, drawPoint);
is it possible to do this without having a form so that we can have a service running?
Bitmap canvas = new Bitmap(600, 480);
Graphics graph = Graphics.FromImage(canvas);
.. then proceed with drawing on graph.

Categories

Resources