Overloading control drawing in c# has text rendering problems - c#

I've sub-classed a control (ToolStripStatusLabel) to try and override the way it paints. At the moment I would expect this code to effectively do nothing, but it leads to a strange output:
protected override void OnPaint(PaintEventArgs e)
{
// Create a temp image to draw to and then put that onto the control transparently
using (Bitmap bmp = new Bitmap(this.Width, this.Height))
{
using (Graphics newGraphics = Graphics.FromImage(bmp))
{
// Paint the control to the temp graphics
PaintEventArgs newEvent = new PaintEventArgs(newGraphics, e.ClipRectangle);
base.OnPaint(newEvent);
// Copy the temp image to the control
e.Graphics.Clear(this.BackColor);
e.Graphics.DrawImage(bmp, new Rectangle(0, 0, this.Width, this.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);//, imgAttr);
}
}
}
When I run this code the text on the control comes out very strangely, the expected image is at the top, the actual output is at the bottom:
It looks like when the control is drawing the text the alpha blending with the antialiased text is going wrong.
Things that I've tried:
Setting the CompositingMode of e.graphics and newGraphics
Setting the TextRenderingHint.
setting the pixel format of newGraphics to 32Bpp ARGB and Premultiplied ARGB
Clearing the newGraphics with the controls background colour before asking the base class to render.

TL;DR: You'll need to render the text yourself with a custom renderer that re-implements OnRenderItemText, probably using graphics.DrawString() to do the drawing ultimately.
Another option would be to use a label in the status bar (as mentioned by #Reza Aghaei). Then you can set UseCompatibleTextRendering to true to make it use GDI+ rather than GDI
This seems to be an inherent problem in the way that the text is rendered at the lowest level. If you add a normal ToolStripStatusLabel and set its TextDirection to be Vertical90 then you get the same result, where the anti-aliasing of the text appears to have no alpha with the background.
Looking at the source you'll see that a very similar bit of code is called where the text is rendered to a bitmap and then in this case rotated:
using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height,PixelFormat.Format32bppPArgb)) {
using (Graphics textGraphics = Graphics.FromImage(textBmp)) {
// now draw the text..
textGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
TextRenderer.DrawText(textGraphics, text, textFont, new Rectangle(Point.Empty, textSize), textColor, textFormat);
textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
g.DrawImage(textBmp, textRect);
}
}
So this seems like a fundamental problem when text is rendered to a bitmaps graphics context (as opposed to the control's graphics context). Ultimately the code that is called is:
using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags ))
{
using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) {
wgr.WindowsGraphics.DrawText( text, wf, bounds, foreColor, GetIntTextFormatFlags( flags ) );
}
}
Which I think is wading off into GDI (as opposed to GDI+) which has trouble with alpha on text.
Your best bet is to write a custom renderer that re-implements OnRenderItemText, probably with some 'inspiration' from the source from the default implementation.

Related

Graphics is blank when trying to turn anti-aliasing off for a bitmap (C#)

What I'm trying to do:
Since in my bitmaps there are some unwanted white edges around the picture that result from anti-aliasing as pointed out from another user from stackoverflow.
I'm trying to convert an image that's inputted into a bitmap, convert bitmap into a Graphics object so that I can set the Smooth Mode to none, and then finally convert that Graphics object to a bitmap so that it can be copied by the user after setting it to the clipboard. I'm not sure if this is a good way of getting rid anti-aliasing in bitmaps but I'm definitely interested in improvements and suggestions.
The issue I'm facing:
The result of the image after is completely blank and does not contain any of the pixels that are previously found in the original bitmap. Here's the result:
This issue applies to all pictures no matter what their format is.
My code:
public PicGen(PictureBox pictureBox)
{
Clipboard.Clear();
Bitmap firstImage = new(pictureBox.Image, pictureBox.Width, pictureBox.Height);
RectangleF cloneRect = new RectangleF(0, 0, firstImage.Width, firstImage.Height);
System.Drawing.Imaging.PixelFormat format = firstImage.PixelFormat;
Bitmap cloneBitmap = firstImage.Clone(cloneRect, format);
Graphics AntiARemover = Graphics.FromImage(cloneBitmap);
AntiARemover.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
Bitmap finalImg = new(52, 52, AntiARemover);
Clipboard.SetImage(finalImg);
Color backColorBottom = firstImage.GetPixel(0, 0);
firstImage.ReplaceColor(backColorBottom, Color.FromArgb(54, 57, 63));
Bitmap finalImg = new(52, 52, AntiARemover);
From the documentation for this bitmap constructor:
The new Bitmap that this method creates takes its horizontal and vertical resolution from the DpiX and DpiY properties of g, respectively.
If you want create a new image with the content from another you need to call one of the DrawImage methods. You should also dispose your graphics object, and any temporary bitmaps you may use.
using var finalImg = new Bitmap(52,52);
using var graphics = Graphics.FromImage(finalImg);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
graphics.DrawImage(cloneBitmap)
However, edge artifacts typically occur when combining two images using an alpha channel, see Premultiplied alpha. In your example I can only see one input image, so I'm really not sure what it is you are actually trying to do. If you need to convert to premultiplied alpha you can use the following code to convert the color for each pixel
premultiplied.R = (byte)(straight.R * straight.A / 255);
premultiplied.G = (byte)(straight.G * straight.A / 255);
premultiplied.B = (byte)(straight.B * straight.A / 255);
premultiplied.A = straight.A;

Graphics.DrawString renders text with black outline on a transparent background

I'm drawing a string on a Bitmap with transparent background using Graphics.DrawString() and I get text with a black contour, when the Font size is smaller than 23 millimeters (the Font is created with GraphicsUnit.Millimeter).
Code:
Bitmap bmp = new Bitmap(2000, 2000);
Color alpha = Color.FromArgb(0, 0, 0, 0);
for (int x = 0; x < bmp.Width; x++)
for (int y = 0; y < bmp.Height; y++)
bmp.SetPixel(x, y, alpha);
Graphics g = Graphics.FromImage(bmp);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
Font labelFont = new Font("Cascadia Mono SemiBold", 23/*22*/, FontStyle.Regular, GraphicsUnit.Millimeter);
Brush brush = new SolidBrush(Color.White);
g.DrawString("Some text", labelFont, brush, 200, 200);
23 Millimeters-Units font:
22 Millimeters-Units font:
I tried to use TextRenderer, but this draws text without transparent background.
The code presented here has multiple problems:
The initial loop is counter-productive for multiple reasons:
Tries to fill a Bitmap with a transparent color, but this is already the non-color associated with a newly created Bitmap (Color.FromArb(0, 0, 0, 0))
Uses the SetPixel() method, the slowest possible tool for the task
If needed, a Bitmap can be filled with a Color using the Graphics.Clear() method, which calls a native GDI+ function to perform the task
Setting an InterpolationMode in this context is not useful, this property selects the algorithm used to scale or rotate images
The SmoothingMode property selects the algorithm used to anti-aliasing lines, curves and the edges of filled areas. It doesn't apply to the rendering of Fonts, so has no effect on the drawn text. It applies to text rendered with a GraphicsPath, since the text is converted to curves
None of the disposable objects (Graphics, Font, Brush) is either disposed explicitly or declared with using statements (which is pretty bad). It's not clear when the Bitmap is disposed, but could be the duty of the code that uses it
To specify the rendering mode of Fonts, the TextRenderingHint property is used instead. Since it's not specified, the System default smoothing of Font is used, usually ClearType.
About this rendering form, see the notes in:
Drawing a Long String on to a Bitmap results in Drawing Issues
ClearType uses intra-pixel smoothing, designed initially for LCD screens, to blend text with a background; it's especially effective with small Fonts sizes. It doesn't support alpha colors (not in this context, at least).
The device context in which the text is rendered, a GDI+ MemoryBitmap, doesn't use or understand this type of hinting (smoothing), so the pixels that fail to render are filled with an empty color, which notoriously appears as black
A black-ish contour might manifests with different Font sizes (not just the measures reported in the question), when the ClearType hinting fill is less than one pixel
To fix the rendering, remove the clutter, specify a suitable TextRenderingHint mode and declare correctly all disposable objects.
I'm not including the Bitmap, because I don't know how it's used. It must be disposed at some point, of course (very important, it allocates unmanaged resources, the Garbage Collector cannot help you)
var bmp = new Bitmap(2000, 2000);
using (var g = Graphics.FromImage(bmp))
using (var font = new Font("Cascadia Mono SemiBold", 22, FontStyle.Regular, GraphicsUnit.Millimeter))
using (var brush = new SolidBrush(Color.White)) {
g.CompositingQuality = CompositingQuality.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.DrawString("Some text", font, brush, 200, 200);
}
TextRenderingHint.AntiAliasGridFit is appropriate here (see also the linked notes), the characters are drawn using their anti-aliased glyph bitmap and hinting (smoothing)
TextRenderingHint.AntiAlias can also be used in this context (and costs slightly less)
CompositingQuality.HighQuality is not actually used here, there isn't really any composition, since no image is rendered against a background (which may require gamma correction), but also has no cost. You can keep it, in case you decide to draw a bitmap onto the current, at some point; or simply remove it.
About TextRenderer draws text without transparent background
This is not correct. TextRenderer (GDI) can of course render text with a transparent background, it just doesn't support an alpha color (in this context)
As mentioned, we're working with an in-memory GDI+ Device Context
But, if you draw the same text in a different Device Context, e.g., the surface of a Control, then things change.
Also note that TextRenderer cannot be used to render text when printing (for the same reasons previously described).
Test this code, subscribing to the Paint event of a PictureBox, also adding a background Image (without a background image the result doesn't change, it's just more visible)
Graphics.DrawString() is used to render text with a semi-transparent (ARGB) Color
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.Top;
private void someControl_Paint(object sender, PaintEventArgs e)
{
using (var font = new Font("Segoe UI", 22, FontStyle.Regular, GraphicsUnit.Millimeter))
using (var brush = new SolidBrush(Color.White)) {
TextRenderer.DrawText(e.Graphics, "Some text", font,
new Rectangle(new Point(0, 10), pictureBox1.ClientSize), Color.White, Color.Transparent, flags);
e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
e.Graphics.DrawString("Some text", font, brush, 0, 130);
}
using (Font font1 = new Font("Segoe UI", 8.0f, FontStyle.Regular, GraphicsUnit.Millimeter))
using (Font font2 = new Font("Segoe UI", 5.5f, FontStyle.Regular, GraphicsUnit.Millimeter))
using (var brush = new SolidBrush(Color.FromArgb(100, Color.Black))) {
e.Graphics.DrawString("← TextRenderer", font1, brush, 610, 70);
e.Graphics.DrawString("ForeColor: White, BackColor: Transparent", font2, brush, 610, 110);
e.Graphics.DrawString("← GDI+ Graphics", font1, brush, 610, 190);
e.Graphics.DrawString("ForeColor: White, Hinting: AntiAliasGridFit", font2, brush, 610, 230);
}
}
Resulting in (enlarge it):

DrawImage() 'sprite' not showing up

I'm attempting to use a custom built .PNG file of letters from the alphabet to give my game some nice looking textual graphics. However, since the core functionality of my WinForms game works using minimal graphics (I have a timer set to fire a little animation routine that fades out the word "Guessed" when a user enters a word that they've already tried - this is done using DrawString()). Right now I'm trying to get DrawImage(Image, dstRect, srcRect, Unit) to work, and I have it set to run on form load.
private void DrawLetters()
{
// Create image.
Graphics letters = this.CreateGraphics();
Image newImage = Image.FromFile(strPath + "Letter_Map.png");
// Create rectangle for displaying image.
Rectangle destRect = new Rectangle(25, 25, 80, 80);
// Create rectangle for source image.
Rectangle srcRect = new Rectangle(0, 0, 833, 833);
GraphicsUnit units = GraphicsUnit.Pixel;
// Draw image to screen.
letters.DrawImage(newImage, destRect, srcRect, units);
}
This is practically verbatim from the MSDN site. My form populates with an array of Labels right now to show the user the grid of letters needed for the game. Is it them being drawn that overwrites the custom rectangle? I want to replace them all with images eventually. I understand srcRect to be (x, y, width, height) so I gave it the full size of the 'spritesheet'. For dstRect I only want it to place a block 80x80px on the form starting around 25x, 25y.
For the heck of it I created a blank form and called my DrawLetters() function during that form load event (I copied the function into that Form's code). I saw nothing, though, so I am starting to get a bit confused. I may need some education about just HOW the drawing works in conjunction with forms and controls being drawn on screen.
EDIT This https://stackoverflow.com/questions/837423/render-a-section-of-an-image-to-a-bitmap-c-sharp-winforms was what initially got me going, but this user has a working knowledge of XNA and seems to be trying to combine that with WinForms. XNA would be overkill, I believe, for the simple text game I am trying to 'pretty up'.
You need to override the forms OnPaintMethod to get access to the forms Graphics object which you can then use to display the image on the form.
If you want to display a portion of the image, you will need to use a different overload of DrawImage, as follows:
public partial class DrawImageDemo : Form
{
public DrawImageDemo()
{
InitializeComponent();
}
private Image _sprites;
public Image Sprites
{
get
{
if (_sprites == null)
{
_sprites = Image.FromFile("test.jpg");
}
return _sprites;
}
}
protected override void OnPaint(PaintEventArgs e)
{
// The forms graphics object
Graphics g = e.Graphics;
// Portion of original image to display
Rectangle region = new Rectangle(0, 0, 80, 80);
g.DrawImage(Sprites, 25, 25, region, GraphicsUnit.Pixel);
base.OnPaint(e);
}
}

Drawing in Winforms

I have written this code, however, it doesn't work. Not only will this not work, but none of the methods I have tried for drawing have worked. I've spent more than an hour or two trying to solve this, but to no success. Ive tried simple programs where all it does is display a small line, but it wont work no matter what i do :c
What am I doing wrong, or what could cause this?
private void pictureBox1_MouseDown(object sender,
MouseEventArgs m,
EventArgs e,
PaintEventArgs q)
{
if (m.Button == System.Windows.Forms.MouseButtons.Left)
{
Point currpoint = System.Windows.Forms.Cursor.Position;
Point origin = new Point(0, 0);
decimal sizee = nud.Value;
int size = Convert.ToInt32(sizee);
Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255),
randonGen.Next(255),
randonGen.Next(255));
Pen selPen = new Pen(randomColor, size);
Graphics g = Graphics.FromImage(pictureBox1.Image);
g.DrawLine(selPen, 3, 3, 133, 133);
}
}
Try adding a
pictureBox1.Invalidate();
call.
This is not the right way to draw to a picture box:
private void pictureBox1_MouseDown(object sender,
MouseEventArgs m,
EventArgs e,
PaintEventArgs q)
{
if (m.Button == System.Windows.Forms.MouseButtons.Left)
{
Point currpoint = System.Windows.Forms.Cursor.Position;
Point origin = new Point(0, 0);
decimal sizee = nud.Value;
int size = Convert.ToInt32(sizee);
Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255),
randonGen.Next(255),
randonGen.Next(255));
Pen selPen = new Pen(randomColor, size);
using(Graphics g = pictureBox1.CreateGraphics()) // Use the CreateGraphics method to create a graphic and draw on the picture box. Use using in order to free the graphics resources.
{
g.DrawLine(selPen, 3, 3, 133, 133);
}
}
}
Btw, this method will create a temporary image which is reseted when the control is invalidated. For a more persistent drawing, you need to listen to the Paint event of the picture box and draw your graphics there.
You must draw it from image first. then attach it to pictureBox1
Bitmap canvas = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(canvas);
Point currpoint = System.Windows.Forms.Cursor.Position;
Point origin = new Point(0, 0);
decimal sizee = nud.Value;
int size = Convert.ToInt32(sizee);
Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255),
randonGen.Next(255),
randonGen.Next(255));
Pen selPen = new Pen(randomColor, size);
g.DrawLine(selPen, 3, 3, 133, 133);
pictureBox1.image = canvas;
This is an old question and if anyone else has a similar problem. See below. First let's examine the Ops code.
(1) See code: The first recommended change is to keep the Pen's format simple until we have a better understanding about how the Pen actually works when drawing to graphics. Look at the Op's line where we create graphics from image which is a perfectly good example of how to directly draw ("which means to write") to the supplied bitmap by use of the bitmap's graphics context. Next, the Op provides an excellent example of the Graphics DrawLine method which can draw the defined line to the supplied bitmap.
(2) Due to missing details we have to make the following assumptions about the Op's supplied bitmap and about their method for drawing a line to the bitmap. Assuming there already exists an image inside this pictureBox1; if an image is not set the graphics we get from image will be from a null image or that each pixel will be black just as a footnote:
(a) Is the Pen's color unique to the existing bitmap and is the alpha component of the color high enough to actually see the resultant color when it's drawn (when in doubt use a unique solid color or at least set the alpha channel to 255)?
(b) This line the Op wants to draw is starting Left 3, Top 3 to Left 133 and that is 3-pixels to the right of bitmap's left side where this line has a height of 133 and as such the Pen's line size was changed to a width = 3 for demonstration purposes.
(c) The final consideration, is the pictureBox1.Size sufficient for us to see this drawn line? The line's geometry forms a rectangle similar to this RectangleF(3, 3, 3, 133) structure, so if the pictureBox1 Bounds rectangle intersects with the derived line's rectangle then the area of that intersection is where the line could be drawn and considered visible.
Before we can draw to the pictureBox1 image from graphics we must first convert the pictureBox1 image data back to a usable image type like a bitmap for example. The reason is the picture box stores only pixel data in array format and is not directly usable by GDI/GDI+ without conversion to an image type ie. bitamp, jpeg, png etc..
One can avoid this messy conversion if you handle you own painting by the way of a custom user control and by properly handling the PaintEventArgs OnPaint implementation and/or by using related graphics screen buffer context scenarios.
For those who just want the answer about what's missing:
private void button1_Click(Object sender, EventArgs e)
{
Pen selPen = new Pen(Color.Red, 2); // The Op uses random color which is not good idea for testing so we'll choose a solid color not on the existing bitmap and we'll confine our Pen's line size to 2 until we know what we're doing.
// Unfortionately the picture box "image" once loaded is not directly usable afterwords.
// We need tp recreate the pictureBox1 image to a usable form, being the "newBmp", and for efficiency the bitmap type is chosen
Bitmap newBmp = new Bitmap(pictureBox1.Width, pictureBox1.Height, PixelFormat.Format32bppArgb); // Tip: Using System.Drawing.Imaging for pixel format which uses same pixel format as screen for speed
// We create the graphics from our new and empty bitmap container
Graphics g = Graphics.FromImage(newBmp);
// Next we draw the pictureBox1 data array to our equivelent sized bitmap container
g.DrawImage(pictureBox1.Image, 0, 0);
g.DrawLine(selPen, 3, 3, 3, 133); // Format: (pen, x1, y1, x2, y2)
pictureBox1.Image = newBmp;
// Don't forget to dispose of no longer needed resources
g.Dispose();
selPen.Dispose();
newBmp.Dispose(); // or save newBmp to file before dispose ie. newBmp.Save("yourfilepath", ImageFormat.Jpeg) or in whatever image type you disire;
}
The Op's code so far only draws a line to the bitmap's surface next if we are to "see" this change we must either save bitmap to file to be viewed later in an image viewer or we must draw the updated bitmap to our display monitor, the screen.
There are several methods with which to draw to your monitor's screen. The most common graphics contexts one could use are Control.CreateGraghics, graphics to screen method from (PaintEventArgs) and/or by using a graphics screen buffer sometimes called and used as a manual double buffered graphics context in which all is implemented by the way of DrawImage method from graphics.
The simplest solution, in this case based upon the Op's own code, is to display this newly updated bitmap using the pictureBox1 control. We'll simply update the control's image with the newly updated bitmap of course once first converted to a usage graphics image as seen in the above code descriptions.
Happy coding!

Merging graphics objects does not render text correctly

I'm trying to solve a problem with a custom control ported from a VCL C++ application. The idea is that individual parts of the control are drawn first on a new Graphics object and then merged with the Graphics object from the control's paint method.
I've created a simplified example:
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
public class Form1 : Form
{
private PictureBox pictureBox;
public Form1()
{
pictureBox = new PictureBox();
pictureBox.Dock = DockStyle.Fill;
pictureBox.Paint += new PaintEventHandler(pictureBox_Paint);
ClientSize = new Size(100, 50);
Controls.Add(pictureBox);
}
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
SolidBrush blackBrush = new SolidBrush(Color.Black);
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
Graphics graphics = Graphics.FromImage(bitmap);
Font font = new Font(pictureBox.Font, FontStyle.Regular);
graphics.DrawString("simple test", font, Brushes.Black, 0, 0);
e.Graphics.DrawImage(bitmap, 0, 0);
}
}
}
Running the above code results in the text being drawn too thick:
When i modify the code to draw the text directly to the Graphics object of the PictureBox i get the correct result:
This problem only occurs with text rendering. Lines and other shapes are rendered correctly. Any ideas how to solve this?
Thanks in advance.
This happens because you forgot to initialize the bitmap pixels. By default they are Color.Transparent, which is black with an alpha of 0. This goes wrong when you draw anti-aliased text into the bitmap, the aliasing algorithm will draw pixels that blend from the foreground (black) to the background (also black). Blobby letters that are not anti-aliased is the result.
This is not a problem in the 2nd screenshot because the background pixels were drawn to battleship gray by the default Form.OnPaintBackground() method. Simply add the Graphics.Clear() method to fix your problem:
using (var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height)) {
using (var graphics = Graphics.FromImage(bitmap)) {
graphics.Clear(this.BackColor); // <== NOTE: added
graphics.DrawString("simple test", pictureBox1.Font, Brushes.Black, 0, 0);
}
e.Graphics.DrawImage(bitmap, 0, 0);
}
With using statements added to prevent your program from crashing when the garbage collector doesn't run often enough.

Categories