Yes, there are ways. With C # 3.0, you have a Func<T> type that does this.
For example, I wrote this yesterday:
var image = Image.FromFile(_file); int height = image.Height; int width = image.Width; double tan = height*1.00/width; double angle = (180.0 * Math.Atan(tan) / Math.PI); var bitmap = new System.Drawing.Bitmap(image, width, height); var g = System.Drawing.Graphics.FromImage(bitmap); int fontsize = 26; // starting guess Font font = null; System.Drawing.SizeF size; Func<SizeF,double> angledWidth = new Func<SizeF,double>( (x) => { double z = x.Height * Math.Sin(angle) + x.Width * Math.Cos(angle); return z; });
The goal was to add a watermark to the existing image. I would like to make the text size of the watermark approximately 85% of the width of the image. But I wanted to overlay the text of the watermark so that it was written at an angle. This showed that some trigger calculations based on angles were necessary, and I wanted to do a little work. Func perfect for this.
In the above code, the Func function (function) is defined, which takes SizeF and returns a double , for the actual width of the text when it is drawn at a given angle. This Func is a variable inside the function, and the variable itself contains the function (reference to a). Then I can call this "private" function within the scope where I defined it. Func has access to other variables that are defined before it in the runtime. Thus, the angle variable is available in the angledWidth() function.
If you want an invokable logic that returns void , you can use Action<T> in the same way..NET defines Func generators that take N arguments, so you can make them pretty complicated. Func is like a VB function or a C # method that returns a non-void; The action is similar to a VB Sub or a C # method that returns void.
Cheeso May 04 '11 at 13:45 2011-05-04 13:45
source share