• 0

[C#] Drawing outline text


Question

Recommended Posts

  • 0

It's pretty easy.

From Windows Forms Programming in C# by Chris Sells

GraphicsPath GetStringPath( string s, float dpi, RectangleF rect, Font font, StringFormat format)
{
    GraphicsPath path = new GraphicsPath();
    // Convert font size into appropriate coordinates
    float emSize = dpi * font.SizeInPoints / 72;
    path.AddString(s, font.FontFamily, (int)font.Style, emSize, rect, format);

    return path;
}

void Form_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    string s = "Outline";
    RectangleF rect = this.ClientRectangle;
    Font font = this.Font;
    StringFormat format = StringFormat.GenericTypographic;
    float dpi = g.DpiY;
    using( GraphicsPath = GetStringPath(s, dpi, rect, font, format) )
    {
        g.DrawPath(Pens.Black, path);
    }
}

  • 0
I want it to have an inner white color and a shadow. Do you think it is possible ?

It's possible.

In the paint event.

  	Graphics g = e.Graphics;
  	string s = "Outline";
  	RectangleF rect = this.ClientRectangle;
  	Font font = this.Font;
  	StringFormat format = StringFormat.GenericTypographic;
  	float dpi = g.DpiY;
  	using( GraphicsPath path = GetStringPath(s, dpi, rect, font, format) )
  	{	
    g.SmoothingMode = SmoothingMode.AntiAlias;
    RectangleF off = rect;
    off.Offset( 5, 5 );
    using( GraphicsPath offPath = GetStringPath(s, dpi, off, font, format) )
    {
    	Brush b = new SolidBrush(Color.FromArgb(100, 0, 0, 0));
    	g.FillPath(b, offPath);
    	b.Dispose();
    }
    g.FillPath(Brushes.White, path);
    g.DrawPath(Pens.Black, path);
  	}

Edited by weenur
  • 0
:laugh: Thanks a lot weenur - that's really close  :D Can I make the shadow even more smooth? Is there a way I can control the shadow width?

585273695[/snapback]

You want that with ice cream? :p

You basically want a blur on the shadow, no?

Edited by weenur
  • 0
Yes - I'm really sorry that I bother you  :blush:  :rolleyes: I didn't mean to do it. I was too rude  :unsure:  it's not urgent so if you have time I'll apprreciate your answer.

585274184[/snapback]

No sweat. I'm just giving you grief. ;)

I should be able to have an example for you as soon as I get some time. I also need to figure out how to convert a region to a bitmap. <anyone?>

  • 0

I'm converting the GraphicsPath to a Region, and then from a Region to a Bitmap to perform raster operations on it. I see what Bob is doing. That's cool. The guy is a guru. I was actually going to do a gaussian blur on the shadow and make it adjustable. I'm just drawing a blank on how to make a Bitmap from a Region.

Region class

  • 0
I'm converting the GraphicsPath to a Region, and then from a Region to a Bitmap to perform raster operations on it. I see what Bob is doing. That's cool. The guy is a guru. I was actually going to do a gaussian blur on the shadow and make it adjustable. I'm just drawing a blank on how to make a Bitmap from a Region.

Region class

585276170[/snapback]

Yes but a Region is simply that - a region. So to turn it into a Bitmap you need to use the region on a Bitmap e.g. Create a new Bitmap of the appropriate dimensions then use Graphics.FillRegion with a suitable Brush. Or am I missing something?

  • 0
Yes but a Region is simply that - a region. So to turn it into a Bitmap you need to use the region on a Bitmap e.g. Create a new Bitmap of the appropriate dimensions then use Graphics.FillRegion with a suitable Brush. Or am I missing something?

585276240[/snapback]

See... that's what I couldn't remember. :D Thanks. It's been a while since I've done any GDI/+ to any extent.

  • 0
See... that's what I couldn't remember. :D Thanks. It's been a while since I've done any GDI/+ to any extent.

585276814[/snapback]

Funny...you virtually answered your own question with your previous post when you said "I'm just drawing a blank on how to make a Bitmap from a Region."! :p

  • 0
Funny...you virtually answered your own question with your previous post when you said "I'm just drawing a blank on how to make a Bitmap from a Region."!  :p

585276872[/snapback]

lmao! I didn't even catch that. I've been staying up too late playing World of Warcraft. :)

  • 0

OK, yyy. If this doesn't do it for you, use Bob Powell's version. You can, of course, modify it to your liking, and set it up to be configurable.

First, add the Filters.cs file to your project. ( get it here )

<edit> you should dispose of the Regions when you're done, as well as the Bitmap.

// In the paint handler
  	Graphics g = e.Graphics;
  	string s = "Outline";
  	Font font = this.Font;
  	RectangleF rect = this.ClientRectangle;
  	StringFormat format = StringFormat.GenericTypographic;
  	float dpi = g.DpiY;
  	using( GraphicsPath path = GetStringPath(s, dpi, rect, font, format) )
  	{	
    g.SmoothingMode = SmoothingMode.AntiAlias;
    RectangleF off = rect;
    off.Offset( 2, 2 );
    Bitmap bmp = null;
    using( GraphicsPath offPath = GetStringPath(s, dpi, off, font, format) )
    {
    	bmp = new Bitmap((int)rect.Width, (int)rect.Height);
    	Graphics g2 = Graphics.FromImage(bmp);
    	g2.CompositingMode = CompositingMode.SourceOver;
    	g2.CompositingQuality = CompositingQuality.HighQuality;
    	g2.SmoothingMode = SmoothingMode.AntiAlias;
    	Brush b = new SolidBrush(Color.FromArgb(200, 0, 0, 0));
    	Region r = new Region(offPath);
    	Region rxor = new Region(rect);
    	g2.FillRegion(SystemBrushes.Control, rxor);
    	rxor.Xor(r);
    	g2.FillRegion(b, r);
    	BitmapFilter.GaussianBlur(bmp, 4);
    	BitmapFilter.GaussianBlur(bmp, 4);
    	BitmapFilter.GaussianBlur(bmp, 4);
    	BitmapFilter.GaussianBlur(bmp, 4);
    	BitmapFilter.GaussianBlur(bmp, 4);
    	b.Dispose();
    	g2.Dispose();
    }
    if( bmp != null )
    {
    	// draw the image
    	g.DrawImage(bmp, off);
    }
    g.FillPath(Brushes.White, path);
    g.DrawPath(Pens.Black, path);
  	}
  }

  • 0

Wow :laugh: it works great :cool:

I just have 2 questions:

1. Are you sure that this source code (and the filters.cs file) are free to use and ditrobute ? I need this code for a freeware application which I plan to distrobute freely with the source code so I need to be sure.

2. This is not so important but I was wondering if there's a way to reduce the Memory usage of that code - it raises the application's Memory usage by about 3 MB I think. It's not that bad but I just wonder.

Thanks again for helping me :)

  • 0

1. Ask the author. I'm sure that as long as you give credit where credit is due, you'll be fine. He is posting it for teaching purposes.

2. I'd have to look more closely at his code. I'm fairly certain that he's managed his memory properly. You could try doing a GC.Collect() at the end of the Paint event. I kind of doubt it'll help, but you never know. Is that memory footprint in release mode, or debug?

  • 0
1. Ask the author. I'm sure that as long as you give credit where credit is due, you'll be fine. He is posting it for teaching purposes.

2. I'd have to look more closely at his code. I'm fairly certain that he's managed his memory properly. You could try doing a GC.Collect() at the end of the Paint event. I kind of doubt it'll help, but you never know. Is that memory footprint in release mode, or debug?

585281673[/snapback]

Ok, I'll ask him.

You don't need to look at the code - that's Ok. I was just wondering if there's a fast way to do it but you are right - probably the code's writer already thought of the memory issue. It isn't that bad after all. I think it is in the release mode.

  • 0
I can't ask the "Windows Forms Programming in C#"  book's author - I don't have his E-mail and I don't think he'll allow me to use that code since it was written in a book. Nevermind - I'll do something else.

585285520[/snapback]

Uh... use it.

Permission is granted to anyone to use this software for any purpose, including commercial applications, subject to the following restrictions

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is requested, as shown here:

Portions copyright ? 2003 Chris Sells (http://www.sellsbrothers.com/).

 

2. No substantial portion of this source code may be redistributed without the express written permission of the copyright holders, where "substantial" is defined as enough code to be recognizably from this code.

  • 0
2. No substantial portion of this source code may be redistributed without the express written permission of the copyright holders, where "substantial" is defined as enough code to be recognizably from this code.

It's pretty explicit - if you are going to distribute the source of your project and it contains a "recognisable portion" of the books sample source code, then you will need to obtain permission from Chris Sells. So just drop him a mail at [email protected] - he may even give you some advice on the memory footprint.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft Edge 149.0.4022.80 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.80 changelog: Fixes Fixed an issue that prevented QR code generation from working. Feature updates Intune MAM Protected Downloads. The protected downloads feature for Intune MAM will now save downloaded files to the Documents > Microsoft Edge > Downloads folder in OneDrive. Extensions monitoring in the Edge management service. The Microsoft Edge management service now allows admins to gain visibility into extensions installed across their managed users. From the extensions monitoring page, admins can see which extensions have been installed as well as manage user requests for blocked extensions. For more information, see Microsoft Edge Extensions Monitoring. Validate Edge builds early with enterprise preview. Enterprise preview provides a simpler way for admins to flight pre-release Edge builds to their users. To reduce friction and bolster usage, users will receive pre-release builds directly inside of their Stable Edge application. Admins can allow users to easily opt-out of the preview experience, using built-in rollback to switch between their pre-release and stable channels with ease. Microsoft 365 admin center users can configure the feature, view their flighting population, and receive personalized recommendations all in one place. For more information, see Get started with Enterprise Preview in Microsoft Edge. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The machines are starting to fight back any way they can.
    • No news articles about the Arch Linux repo being majorly infected with malware?!?
    • Waymo recalls self-driving software after cars enter closed freeway work zones by Paul Hill Waymo, the self-driving car maker owned by Alphabet – the parent company of Google –, has recalled some of its fifth-generation Automated Driving Systems (ADS). It did so after some of its cars drove through closed construction zones. According to the National Highway Traffic Safety Administration (NHTSA), the affected vehicles were capable of driving through a closed freeway construction zone and continuing to drive at speed. The listing on the NHTSA website says that Waymo is currently developing a solution to fix this issue, but in the meantime, freeway driving is being restricted. Waymo will update its ADS software so that vehicles can detect when they can avoid entering construction zones. According to the Safety Recall Report, on April 20, 2026, Waymo’s Field Safety Committee began meetings reviewing an event from April 11, 2026, and five events from April 19, 2026, where Waymo’s autonomous vehicles didn’t recognize and drove past ramp closure signs into the pre-planned freeway construction zones. This took place in Phoenix, Arizona. Separately, on May 18, 2026, seven Waymo vehicles entered freeway lanes with active construction in the San Francisco Bay Area by driving between cones that were placed to show the lane was closed. On the back of both of these events, Waymo restricted freeway driving until it could address the issue. In June, Waymo’s Safety Board reviewed the issue and additional information related to ADS performances around construction zones; then, as a result, it decided to conduct a recall. This development is not good for Waymo as it adds to a growing list of technical hiccups its cars have experienced. Ultimately, it will lead to more scrutiny from lawmakers around the world who will be more cautious about letting autonomous vehicles on their roads without tighter regulation. For readers in areas where Waymo operates, does this news make you more wary about stepping into one of these vehicles?
    • I'm still on Windows 10 22H2 because I didn't want to deal with all the issues in Windows 11, so I waited almost a week before installing the latest Patch Tuesday update (KB5094127), I went ahead and did it, and it was a huge mistake—ever since then, my File Explorer has seen a performance drop of about 30% when transferring large files... Once again, Microsoft has outdone itself! This update cannot be uninstalled, either through the Control Panel (via Settings) or by accessing Advanced Startup Options. The only possible alternative would be to use system restore points, but I’d have to reinstall all app and driver updates (and there’s no guarantee it would work). Or there’s the “nuclear option” of a in-place repair without losing files or apps, but even then, all my customizations would be lost! Microsoft just can’t help but mess everything up! Way to go, Microsoft! But I still don’t want your c****y Windows 11!
  • Recent Achievements

    • Week One Done
      Eurosoft10 earned a badge
      Week One Done
    • One Month Later
      Eurosoft10 earned a badge
      One Month Later
    • One Year In
      Skeet Campbell earned a badge
      One Year In
    • One Month Later
      Sharbel earned a badge
      One Month Later
    • First Post
      BizSAR earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      599
    2. 2
      +Edouard
      190
    3. 3
      PsYcHoKiLLa
      79
    4. 4
      Michael Scrip
      77
    5. 5
      Steven P.
      70
  • Tell a friend

    Love Neowin? Tell a friend!