• 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

    • Same Internet Archive seemed to grab the new version https://web.archive.org/web/20...d/Setup_MakeMKV_v1.18.4.exe Here's the link to an additional file it periodically downloads https://web.archive.org/web/20260213092148/https://www.makemkv.com/sdf.bin I think update's keys, etc. To manually trigger this update, put the sdf.bin file in the root of where the program is installed. When you launch the program it will pick up the file and import it. Typically put it here: C:\Program Files (x86)\MakeMKV\sdf.bin
    • Windows 11 KB5094126, KB5093998 bugging out Office apps but it may not be Microsoft's fault by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. Although the tech giant did not acknowledge any major problems, some users online reported various issues ranging from OneDrive and Dropbox access problems, BitLocker recovery lockouts, to blue screens and BSODs. You can read about them in this dedicated piece. While there is still no confirmation about those problems from Microsoft the company has admitted to another bug which we did not report on. The tech giant has confirmed it has received reports of an issue in which certain third-party applications may be unable to launch Microsoft Office apps or open Office documents after installing the Patch Tuesday. This affects both Windows 11 as well as Windows 10. The company says the problem impacts a subset of applications that rely on OLE (Object Linking and Embedding) automation to communicate with Microsoft Office programs. According to Microsoft, affected scenarios involve third-party software attempting to open Office applications or documents from within their own interface. In such cases, the Office program may fail to launch altogether, or the requested document may not open. Oddly there may not be any error message, which probably makes the issue difficult to diagnose. The bug affects several Office products, including Word, Excel, PowerPoint, Access, and other apps in the Microsoft Office suite when they are launched through the affected software. These include tax and accounting software such as CCH Engagement and Workpaper Manager, dental practice management solutions like Dentrix and Softdent, as well as the popular research and reference management tool Zotero. Microsoft adds that other applications using similar Office integration methods could also experience the same problematic behavior. To understand the issue it is important to look at OLE, the Microsoft technology involved. OLE allows different applications to work together and share data, while its Automation feature lets one program control another. Thus this enables third-party software to launch Microsoft Office apps, open documents, and perform tasks automatically without requiring users to switch between programs. Because many accounting, healthcare, research, and business applications rely on OLE automation to interact with Word, Excel, PowerPoint, and other Office apps, any disruption can break those workflows. As a result, affected software may be unable to open Office documents or launch Office applications even though the programs themselves continue to work normally. At the moment the company has not provided a permanent fix though it has confirmed that engineers are actively working on a resolution, which will be delivered through a future Windows update. As such additional details will be shared once more information becomes available. In the meantime, Microsoft recommends a simple workaround for affected users whic is to open the Office application or document directly rather than launching it through the third-party program. For enterprise customers and organizations managing larger deployments, Microsoft says an additional mitigation is available. Admins experiencing the problem on their managed devices are advised to contact Microsoft Support for business to obtain and apply the workaround.
    • It saddens me when cars are such dull colours now. Mine is bright metallic blue and I absolutely adore it for standing out in contrast to that depressing backdrop of traffic.
    • Sparkle 2.20.0 by Razvan Serea Sparkle is a free, open-source Windows optimization tool designed to make your PC faster, cleaner, and more private. With Sparkle, you can easily debloat Windows by removing unnecessary apps and services, disable Microsoft tracking to enhance privacy, and apply performance tweaks to boost speed. Its cleaner removes junk and temporary files, while every change is safe and fully reversible. Sparkle also features a modern, user-friendly interface with automatic updates, making system maintenance simple. Explore over 39 tweaks, from disabling telemetry and hibernation to optimizing network and game settings, all aimed at customizing and enhancing your Windows experience. Sparkle supports Windows 10 and 11. Sparkle 2.20.0 changelog: Debloat Tweak has animated border New homepage loading UI New Tweak Modal (Markdown Supported) Refactored GPU Detection Added Tests with vitest Added foobar2000 to apps Added Localsend to apps Updated Modal Styles Added styles for disabled inputs Added Animated Border to debloat-windows tweak Bumped dependencies Refactor System info logic for speed Tweak info modals now support Markdown Added Clear System info cache to settings Redesigned Home Page Loading UI Changed Some Icons around the app Download: Sparkle 2.20.0 | Portable | ~100.0 MB (Open Source) Links: Sparkle Website | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • lol it was a typo, fixed! haha imagine an actual 4TB Gen4 NVMe for $40 in 2026
  • Recent Achievements

    • Reacting Well
      Dys Topia earned a badge
      Reacting Well
    • Conversation Starter
      NovaEdgeX earned a badge
      Conversation Starter
    • One Year In
      Console General earned a badge
      One Year In
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      517
    2. 2
      +Edouard
      184
    3. 3
      PsYcHoKiLLa
      106
    4. 4
      Steven P.
      88
    5. 5
      ATLien_0
      68
  • Tell a friend

    Love Neowin? Tell a friend!