Today I wrote a mini program that requires adding shadows to images. Remember that there are shadow effects in WPF's Effect, so I plan to use it. The code is as follows:
using (var imageStreamSource = (@"r:\")) using (Stream fs = (@"r:\")) { var decoder = (imageStreamSource, , ); var bitmapFrame = [0]; var size = new Size(, ); var img = new Image() { Source = bitmapFrame }; = new (); (new Rect(0,0,,)); var rtb = new RenderTargetBitmap(, , 96, 96, PixelFormats.Pbgra32); (img); var png = new PngBitmapEncoder(); ((rtb)); (fs); }
During use, I found that the processing methods of WPF and GDI are somewhat similar. Its basic usage is as follows:
Image myImage = new Image(); FormattedText text = new FormattedText("ABC", new CultureInfo("en-us"), , new Typeface(, , , new FontStretch()), , ); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = (); (text, new Point(2, 2)); (); RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32); (drawingVisual); = bmp;
The main steps are as follows:
- Drawing in DrawingContext
- Convert DrawingContext to Visual via DrawingVisual
- Convert Visual to BitmapFrame via RenderTargetBitmap
- Save BitmapFrame as an image via xxxBitmapEncoder
These steps do not need to be strictly followed. For example, the first example I first created Visual directly and saved as an image. Actually, I prefer this method because Visual can be displayed directly on the WPF interface, which is convenient for debugging and is very convenient for applying various special effects in WPF. However, remember to call the Arrange function, otherwise you will not see the generated result.
Here is a simpler example for learning.
Ellipse cir = new Ellipse(); = 50; = 50; = ; = 1.0; (new Rect(new Size(50, 50))); //This sentence cannot be missed RenderTargetBitmap rtb = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32); (cir); PngBitmapEncoder png = new PngBitmapEncoder(); ((rtb)); using (Stream fs = (@"r:\")) { (fs); }
This is all about this article about using Effects to add shadow effects to images in C#. I hope it will be helpful to everyone's learning and I hope everyone will support me more.