• 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

    • Nudge me when they bring back hardware audio acceleration so I can get my EAX 5 back. We've evolved graphics to real-time path tracing, but regressed audio some 15 years back in time with this stupid software audio stack.
    • Ocenaudio 3.19.4 by Razvan Serea  Ocenaudio is a full featured, fast and easy to use audio and music editor. It is the ideal software for people who need to edit and analyze audio files without complications. Ocenaudio also has powerful features that will please more advanced users. To assist ocenaudio development, a powerful toolset of audio editing, analysis and manipulation called Ocen Framework was created. ocenaudio is also based on Qt framework, a well known library for cross-platform development. Cross-platform support ocenaudio is available for all major operating systems: Microsoft Windows, Mac OS X and Linux. Native applications are generated for each platform from a common source, in order to achieve excelent performance and seamless integration with the operating system. All versions of ocenaudio have a uniform set of features and the same graphical interface, so the skills you learn in one platform can be used in the others. VST plugins support Ocenaudio supports VST (Virtual Studio Technology) plugins, giving its users access to numerous effects. Like the native effects, VST effects can use real-time preview to aide configuration. Real-time preview of effects Applying effects such as EQ, gain and filtering is an important part of audio editing. However, it is very tricky to get the desired result by adjusting the controls configuration alone: you must listen the processed audio. To ease the configuration of audio effects, ocenaudio has a real time preview feature: you hear the processed signal while adjusting the controls. The effect configuration window also includes a miniature view of the selected audio signal. You can navigate on this miniature view in the same way as you do on the main interface, selecting parts that interest you and listening to the effect result in real time. Multiselection for delicate editions To speed up complex audio files editing, ocenaudio includes multi-selection. With this amazing tool, you can simultaneously select different portions of an audio file and listen, edit or even apply an effect to them. For example, if you want to normalize only the excerpts of an interview where the interviewee is talking, just select them and apply the effect. Eficient edition of large files With ocenaudio, there is no limit to the length or the quantity of the audio files you can edit. Using an advanced memory management system, the application keeps your files open without wasting any of your computer's memory. Even in files several hours long, common editing operations such as copy, cut or paste happen almost instantly. Fully featured spectrogram Besides offering an incredible waveform view of your audio files, ocenaudio has a powerful and complete spectrogram view. In this view, you can analyze the spectral content of your audio signal with maximum clarity. Advanced users will be surprised to find that the spectrogram settings are applied in real time. The display is updated immediately when altering features such as the number of frequency bands, window type and size and dynamic range of the display. Ocenaudio 3.19.4 changelog: Adds fallback fonts so every language and symbol displays correctly Improves autosave and session recovery stability Improves region navigation and display Fixes a crash when the level meter is used on displays with a scaling greater than 200% Fixes memory corruption when using the silence selection tools Fixes crashes when closing a file while effects are still being processed Fixes a freeze when applying effects to many files at once (macOS) Fixes crashes related to audio devices on Windows Fixes invalid file names when exporting regions whose label is used as the file name Other bug fixes and improvements Download: Ocenaudio 64-bit | Portable | ~40.0 MB (Freeware) Download: Ocenaudio for Linux and Mac OS View: Ocenaudio Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Hasleo Disk Clone 5.8.2.1 by Razvan Serea Hasleo Disk Clone is a free and all-in-one disk cloning software for Windows 11/10/8/7/Vista and Windows Server that can help you migrate Windows OS to another disk, clone one disk to another disk or clone one partition to another location quickly and efficiently. Completely Free Windows Migration and Disk/Partition Cloning Software Migrate Windows from one disk to another without reinstalling Windows, apps. Clone one disk to another and makes the data on 2 disks are exactly the same. Clone a partition to another location without losing any data. Easily adjust the size and location of the destination partition. Convert MBR to GPT or convert GPT to MBR by cloning. Creation of Windows PE emergency disk. Extremely fast cloning speed and multi-language support. Supported OS: Windows Vista/Server 2008 or later, fully compatible with GPT and UEFI. Hasleo Disk Clone 5.8.2.1 changelog: Fixed an issue that caused disk enumeration to fail Fixed an issue where WinPE created under Windows ARM64 26H1 did not work properly Download: Hasleo Disk Clone 5.8.2.1 | 32.3 MB (Freeware) Link: Hasleo Disk Clone Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • This got me thinking, would you rather a self driving car prioritise protecting its passengers or everyone else? I'd choose the one that keeps me and my kids safest. At some point, these cars have to make those choices already, don't they? Wonder if we have a way to find out what way they lean.
    • The proportion (or number of iterations) has nothing to with this aspect of Copyright I am describing. In short, it doesn't matter how many times the manager tells you to change something or how. Your work product is always YOURS until and unless you then assign that to the person representing the client/company, usually for financial compensation -- either in salary or as a subcontract work for hire payment. if iterations determined copyright, then businesses would have learned to just keep making changes until they could claim they owned the copyright, without having to compensate the artist for their work. And that would be BAD. The only place where the amount of changes does have a role is in how much does a human modify a previous public domain work (from any source) before it is considered fair use or their own work, etc. For example, if a human makes substantial changes to a public domain (re: AI, by definition) work, then they can then claim that derivative work as their own...but NEVER the original version, of course. That's why anyone can make a movie about Dracula, for example, as long as it is based on the public domain novel, but not if they take new ideas from copyrighted movies made afterwards. As one of the people who personally advised the US Copyright Office on their recent ruling on these very issues, be assured that I specifically used the terminology precisely -- though I made it simple enough for laymen to understand it. If I made this confusing by doing so, I apologize. But, to be clear regarding your assumption that I would agree to your second statement that I quoted above -- the answer is NO. If AI does the work, no matter how much "direction" you give it, it cannot be copyrighted. All AI generated content is in the Public Domain and therefore the copyright cannot be assigned to ANYONE, even you -- until and unless substantial modifications are made to it BY A HUMAN BEING (yourself or a contracted artist/writer/etc.) and then that copyright on the derivative work is legally (in writing) transferred to you. This is a critical distinction. And it is important that people, especially AI sloppers, understand this. For example, YouTube is not paying AI slop generators for the copyright, etc. of their AI slop. What YouTube is doing is sharing AD REVENUE for permission to publish your AI slop. Copyright/ownership/rights never come into it. Importantly, that means that anyone can copy any AI slopware on YouTube, etc. and rehost it anywhere they want, even back on YouTube, and there is nothing legal that YouTube can do about it with regards to copyright protections, ownership, DMCA, etc. Anyone is legally free to use any AI slopware in any way they want. When this ruling was pending, I warned Disney legal of all of this before they did their OpenAI deal -- that it would literally dilute their entire IP portfolio forever. They ignored that warning for the PR and stock bump. But that is why, when the ruling came down last year, Disney quickly extricated themselves from that OpenAI deal, even eating the initial upfront fees -- followed closely by OpenAI ending their entire AI video generating business model. They adjusted their PR release dates to make this less obvious to shareholders, of course. Phew. I hope that this clears up the key distinctions for you and anyone reading. If you have any additional questions or even hypotheticals about AI and Copyright, please feel free to ask.
  • Recent Achievements

    • Collaborator
      ryansurfer98 went up a rank
      Collaborator
    • 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
  • Popular Contributors

    1. 1
      +primortal
      553
    2. 2
      +Edouard
      188
    3. 3
      Michael Scrip
      78
    4. 4
      PsYcHoKiLLa
      74
    5. 5
      neufuse
      71
  • Tell a friend

    Love Neowin? Tell a friend!