How to set fontweight? - c#

I'm writing a simple application in c# .net core 6 and winform to "assemble" some pngs and write some text on it.
This is the Photoshop output. The Title "Baldur the invincible" is wrote in Diablo Light when i'm writing it with DrawString with Font("Diablo", 30, FontStyle.Regular)
and this is my output with the Font.
In photoshop i used Diablo Light font but in the list of system fonts, from C# code, i see just Diablo Regular.. and the result is different.
How i can set the fontweight ?
here some code:
// ---------------------------------------------------------------------------------------------- +
// All TEXT ------------------------------------------------------------------------------------- +
// ---------------------------------------------------------------------------------------------- +
{
//string familyName;
//string familyList = "";
//FontFamily[] fontFamilies;
//InstalledFontCollection installedFontCollection = new InstalledFontCollection();
//fontFamilies = installedFontCollection.Families;
Font title_font = new Font("Diablo", 30, FontStyle.Regular);
Font sub_font = new Font("Diablo", 25, FontStyle.Regular);
List<Font> list_fonts = new List<Font>();
list_fonts.Add(title_font);
list_fonts.Add(sub_font);
RectangleF tit_rect = new RectangleF(165, 70, w - (165 * 2), h);
//RectangleF sub_rect = new RectangleF(165, 82 + 30, w - (165 * 2), h);
var v = m_dict_titles["Title"];
string curr_string = tabbed_value[v].ToUpper();
float offsety = WriteTitleTextf2(map_back, 0, TL(curr_string, false), tit_rect, list_fonts, StringAlignment.Near, 5);
}
public void WriteOnBitmapf(Bitmap bmp, int col, Font font, String text, RectangleF rectf, StringAlignment st_align, float stringi = 0.0f)
{
float size = font.Size;
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
StringFormat format = new StringFormat()
{
Alignment = st_align,
LineAlignment = StringAlignment.Near
};
Brush br = col == 0 ? new SolidBrush(Color.FromArgb(0, 0, 0)) : new SolidBrush(Color.FromArgb(255, 255, 255));
g.DrawString(text, font, br, rectf, format);
g.Flush();
}

Related

How to draw a text in a shape? C#

The question is simple, assuming you have a shape (lets say a rectangle) and a text ("hello" for example), so it'll write the text all accross the borders of the rectangle for as many times as it fits, for example:
hello hello hello hello
hello hello
hello hello
hello hello hello hello
In order to do it I assume you'd need to use a graphics variable, I just dont know how to do it.
A code for drawing a string in a bitmap object:
Bitmap tempp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(tempp);
SizeF w = g.MeasureString("22", new Font("Tahoma", 200));//in order to get the size of the string as a pixel measurement
Bitmap bmp = new Bitmap((int)w.Width+1, (int)w.Height+1);//the bitmap that will contain the text as a picture
RectangleF rectf = new RectangleF(0, 0, (int)w.Width+1, (int)w.Height+1);
g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
g.DrawString("22", new Font("Tahoma", 200), Brushes.Black, rectf, format);
g.Flush();
Thanks in advance.
For second comment:
hello hello hello
hel llo
hel llo
hello hello hello
I hope this is what you need. There isn't much to explain here. The logic is pretty straightforward.
public string MyString = "Hello"
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
var strFont = new Font("Tahoma", 10);
var strSizeF = g.MeasureString(MyString, strFont);
var canvas = new Rectangle
{
Height = 200,
Width = 200,
Location = new Point(10, 10),
};
g.DrawRectangle(new Pen(new SolidBrush(Color.Blue)), canvas);
var nx = (int)(canvas.Width / strSizeF.Width);
var ny = (int)(canvas.Height / strSizeF.Height);
var spacingX = (canvas.Width - nx * strSizeF.Width) / (nx-1);
var spacingY = (canvas.Height - ny * strSizeF.Height) / (ny-1);
//draw top row and bottom row
int i;
for (i = 0; i < nx; i++)
{
g.DrawString(
MyString,
strFont,
Brushes.Black,
new PointF(canvas.X + i*(strSizeF.Width + spacingX), canvas.Y)
);
g.DrawString(
MyString,
strFont,
Brushes.Black,
new PointF(canvas.X + i * (strSizeF.Width + spacingX), canvas.Y + canvas.Height - strSizeF.Height)
);
}
//divide the string into half
var isLengthOdd = MyString.Length % 2 != 0;
var substr1 = MyString.Substring(0, MyString.Length / 2 + (isLengthOdd ? 1 : 0));
var substr2 = MyString.Substring(MyString.Length / 2, MyString.Length - MyString.Length / 2);
var substr2SizeF = g.MeasureString(substr2, strFont);
//draw side rows
for (i = 1; i < ny - 1; i++)
{
g.DrawString(
substr1,
strFont,
Brushes.Black,
new PointF(canvas.X, canvas.Y + i * (strSizeF.Height + spacingY))
);
g.DrawString(
substr2,
strFont,
Brushes.Black,
new PointF(canvas.X + canvas.Width - substr2SizeF.Width, canvas.Y + i * (strSizeF.Height + spacingY))
);
}
}
Result:

System.Drawing quality issue with large offset matrix

I've run into an issue with drawing text and basic graphic drawing operations not having the proper placement & quality when the drawing matrix has large offset values. I've tried number SmoothMode, InterpolationMode, & TextRenderingHint options with no luck.
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public void RenderImageClosePointDrawing()
{
float x = 68336, y = 99460;
PointF anchorPoint = new PointF(17494176, 25461836);
PointF anchorPoint2= new PointF(17494076, 25461836);
string textLabel = "9318";
float textFontSize = 20;
float symbolsize = 34;
string fontFamly = "Arial";
Bitmap bitmap = new Bitmap(256, 256);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
graphics.Transform = new Matrix(1, 0, 0, 1, -x * 256, -y * 256);
//Draw the circle
Pen polyPen = new Pen(new SolidBrush(Color.Black), 2);
Brush polyBrush = new SolidBrush(Color.Teal);
graphics.DrawEllipse(polyPen, anchorPoint.X, anchorPoint.Y, symbolsize, symbolsize);
graphics.FillEllipse(polyBrush, anchorPoint.X, anchorPoint.Y, symbolsize, symbolsize);
RectangleF drawnArea = new RectangleF(anchorPoint.X, anchorPoint.Y, symbolsize, symbolsize);
Pen polyPen2 = new Pen(new SolidBrush(Color.Black), 1);
Brush polyBrush2 = new SolidBrush(Color.Teal);
graphics.DrawEllipse(polyPen2, anchorPoint2.X, anchorPoint2.Y, symbolsize, symbolsize);
graphics.FillEllipse(polyBrush2, anchorPoint2.X, anchorPoint2.Y, symbolsize, symbolsize);
RectangleF drawnArea2 = new RectangleF(anchorPoint2.X, anchorPoint2.Y, symbolsize, symbolsize);
Pen polyPen3 = new Pen(new SolidBrush(Color.Red), 1);
graphics.DrawRectangle(polyPen3, drawnArea.X, drawnArea.Y, drawnArea.Width, drawnArea.Height);
graphics.DrawRectangle(polyPen3, drawnArea2.X, drawnArea2.Y, drawnArea2.Width, drawnArea2.Height);
//Draw the text
Pen textOutlinePen = new Pen(new SolidBrush(Color.Orange), (float)4);
textOutlinePen.EndCap = LineCap.Round;
textOutlinePen.LineJoin = LineJoin.Round;
textOutlinePen.MiterLimit = 0;
Brush textFillBrush = new SolidBrush(Color.Teal);
FontFamily textFontFamily = new FontFamily(fontFamly);
PointF textAnchor = new PointF(anchorPoint.X, anchorPoint.Y);
ShiftTextAnchor_NW(textLabel, textFontSize, ref drawnArea, textFontFamily, ref textAnchor);
var textPath = new GraphicsPath();
textPath.AddString(textLabel,
textFontFamily,
(int)FontStyle.Bold,
textFontSize,
textAnchor,
new StringFormat()
);
graphics.DrawPath(textOutlinePen, textPath);
graphics.FillPath(textFillBrush, textPath);
//Draw the text2
Pen textOutlinePen2 = new Pen(new SolidBrush(Color.Orange), (float)1);
textOutlinePen.EndCap = LineCap.Round;
textOutlinePen.LineJoin = LineJoin.Round;
textOutlinePen.MiterLimit = 0;
PointF textAnchor2 = new PointF(anchorPoint2.X, anchorPoint2.Y);
ShiftTextAnchor_NW(textLabel, textFontSize, ref drawnArea2, textFontFamily, ref textAnchor2);
var textPath2 = new GraphicsPath();
textPath2.AddString(textLabel,
textFontFamily,
(int)FontStyle.Bold,
textFontSize,
textAnchor2,
new StringFormat()
);
graphics.DrawPath(textOutlinePen2, textPath2);
graphics.FillPath(textFillBrush, textPath2);
}
bitmap.Save(#"C:\ClosePointDrawing.png", ImageFormat.Png);
}
private static void ShiftTextAnchor_NW(string textLabel, float textFontSize, ref RectangleF drawnArea, FontFamily textFontFamily, ref PointF textAnchor)
{
GraphicsPath tempPath = new GraphicsPath();
tempPath.AddString(
textLabel,
textFontFamily,
(int)FontStyle.Bold,
textFontSize,
textAnchor,
new StringFormat()
);
var textBounds = tempPath.GetBounds();
var offsetX = textBounds.X - textAnchor.X;
var offsetY = textBounds.Y - textAnchor.Y;
textAnchor = new PointF(drawnArea.Left - (textBounds.Width + offsetX), drawnArea.Top - (textBounds.Height + offsetY));
}
When you run this code you'll get this for output: ClosePointDrawing.png
You'll notice that the text doesn't not look nice (distorted some) and also that the Black stroke outline around the circle is only lined up properly with its Teal color filled circle with the one on the left when using a 1 pixel stroke. The one on the right uses a 2 pixel stroke. You'll also see that the Red Squares are not lined up with the Teal Circle, they should be completely encapsulating it.
Now if you change the first few values in the code so that it doesn't use a large offset as follows:
float x = 0, y = 0;
PointF anchorPoint = new PointF(150, 50);
PointF anchorPoint2 = new PointF(50, 50);
You'll get this for output: ClosePointDrawing2.png
Notice that the Text looks much better, and that the strokes are perfectly lined up with the filled circles as well as the red squares.
Is there anything that can be done, so that it will render it properly with the larger matrix?

Blob doesn`t match tracking object

hi,
I need to use color tracking.
The blob does not match my target object when I run my code in surface pro 4.
but the code is correct when I test it on my Acer.
anyone knows that why?
public void forobject(Bitmap image)//put setted color value into image1
{
BlobCounter blobCounter = new BlobCounter();
blobCounter.MinWidth = 5;
blobCounter.MinHeight = 5;
blobCounter.FilterBlobs = true;
blobCounter.ObjectsOrder = ObjectsOrder.Size;
//Grayscale griFiltre = new Grayscale(0.2125, 0.7154, 0.0721);
//Grayscale griFiltre = new Grayscale(0.2, 0.2, 0.2);
//Bitmap griImage = griFiltre.Apply(image);
BitmapData objectsData = image.LockBits(new Rectangle(0, 0, image.Width/2, image.Height/2), ImageLockMode.ReadOnly, image.PixelFormat);
// grayscaling
Grayscale grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
UnmanagedImage grayImage = grayscaleFilter.Apply(new UnmanagedImage(objectsData));
// unlock image
image.UnlockBits(objectsData);
blobCounter.ProcessImage(image);
Rectangle[] rects = blobCounter.GetObjectsRectangles();
Blob[] blobs = blobCounter.GetObjectsInformation();
pictureBox_tracking.Image = image;//????
if (rdiobtn_singletracking.Checked)
{
// Single Tracking--------
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Rectangle objectRect = rects[0];
//Graphics g = Graphics.FromImage(image);
Graphics g = pictureBox_real.CreateGraphics();
using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
{
g.DrawRectangle(pen, objectRect);
}
//Drawn by the rectangle coordinates is taken away.
//int objectX = objectRect.X; //+ (objectRect.Width / 2);
//int objectY = objectRect.Y; //+ (objectRect.Height / 2);
x = objectRect.X;
y = objectRect.Y;
w = objectRect.Width;
h = objectRect.Height;
// g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));
g.Dispose();
}

How to apply more than one filter to the image using Aforge

I can filter red and blue color separately but i want to filter both at the same time.. so my code is like this
//FOR RED COLOR
ColorFiltering filter = new ColorFiltering();
filter.Red = new IntRange(100, 255);
filter.Green = new IntRange(0, 75);
filter.Blue = new IntRange(0, 75);
filter.ApplyInPlace(image1);
MyDraw(image1);
// FOR BLUE COLOR
EuclideanColorFiltering filter2 = new EuclideanColorFiltering();
filter2.CenterColor = new RGB(Color.FromArgb(9, 39, 101));
filter2.Radius = 50;
filter2.ApplyInPlace(image1);
MyDraw(image1);
public void MyDraw(Bitmap image)
{
BlobCounter blobCounter = new BlobCounter();
blobCounter.MinWidth = 2;
blobCounter.MinHeight = 2;
blobCounter.FilterBlobs = true;
blobCounter.ObjectsOrder = ObjectsOrder.Size;
Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap grayImage = grayFilter.Apply(image);
blobCounter.ProcessImage(grayImage);
Rectangle[] rects = blobCounter.GetObjectsRectangles();
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Rectangle objectRect = rects[0];
//Graphics g = Graphics.FromImage(image);
Graphics g = pictureBox1.CreateGraphics();
reception = "Cam," + objectRect.X + "," + objectRect.Y;
Console.WriteLine("X: " + objectRect.X + " Y:" + objectRect.Y.ToString());
using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
{
g.DrawRectangle(pen, objectRect);
}
int objectX = objectRect.X + (objectRect.Width / 2);
int objectY = objectRect.Y + (objectRect.Height / 2);
g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));
g.Dispose();
}
}
}
So i want to recognize blue and red shapes on webcam and draw a rectangle around recognized shape. For now, I can do it as red or blue. But I want to recognize red and blue colors at the same time
how can i add multiple filters?

Bitmap graphics: when saving on disk no drawed strings - works when memorystream

I am creating a PNG picture, using the Bitmap object, using Drawing.Graphics . I create a Bitmap, insert a background image and draw some strings.
Now, when I save the image on the disk, the files does not have my strings!
I am doing this in ASP.NET MVC, where this is my controllers signature:
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
When I don't save the image on the disk and instead returns a FileStreamResult from a MemoryStream, the image looks perfectly.
So there is some problem that when I save the image to the disk, the strings are "forgotten" somehow.
Any ideas?
My code:
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Save();
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
If in doubt, it is the g.DrawString which is not being saved on the picture.
NEW atttempt (still not working):
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
{
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
//MemoryStream stm = new MemoryStream();
//bmp.Save(stm,System.Drawing.Imaging.ImageFormat.Png);
//stm.Position = 0;
//return new FileStreamResult(stm, "image/png");
}
I can't tell for sure, but it looks like you might be confusing g.Save() with g.Flush().
You need to call g.Flush(FlushIntention.Sync) instead of g.Save(). You should probably also call bmp.Save() outside of the using block:
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
//...
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png)
Save() is used to save the current graphics state so that you can modify it and then restore it later.:
GraphicsState oldState = g.Save();
// Make some changes to the graphics state...
g.Restore(oldState);
Flush() on the other hand, is used to force the graphics object to complete any pending operations. By passing FlushIntention.Sync as a parameter, Flush() won't return until the flushing is complete.

Categories